如何在C#中生成UUID


Answers:


220

您可能正在寻找System.Guid.NewGuid()


33
您还可以执行String UUID = Guid.NewGuid()。ToString()
贾斯汀

10
GUID和UUID都一样吗?
Uma Shankar Subramani

17
@Uma Shankar Subramani:GUID =全局唯一标识符,UUID =全局唯一标识符。相同概念的不同词。
Tudor

1
而且,您需要将GUID格式化为与默认字符串不同的字符串,您可以使用ToString(string format)接受多个格式说明符之一的重载。
Michiel van Oosterhout13年

7
System.Guid.NewGuid().ToString("B").ToUpper()如果您想与某些无法理解小写UUID的MS Build工具兼容,则可能需要这样做。例如,vdproj安装项目的UUID为大写,如果您将其写为小写,则会抛出异常。
Mark Lakata 2013年

43

请注意:.NET Guid和(RFC4122)UUID的字符串表示形式相同,但存储格式却不同。.NET的前三Guid部分以小尾数字节交换。

如果要传输字节(例如,作为base64),则不能只使用Guid.ToByteArray()它并对其进行编码。您将需要Array.Reverse前三个部分(Data1-3)。

我这样做:

var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);

有关特定的.NET实现细节,请参见此答案

编辑:感谢Code Ranger的Jeff Walker指出,内部结构与传入和传出字节数组构造函数和的字节数组的格式无关ToByteArray()


注意:我意识到OP可能意味着Guid(因为它是为.idl设计的),但是我碰到了这个问题。Bingers和Googlers,您来了。
Ben Mosher

1
我无法对此进行测试,但是您确定应该检查BitConverter.IsLittleEndian而不是仅反转。Guid.ToByteArray()的文档调出字节序为小端,并说构造函数匹配。GUID的规范是小端的。我认为应该独立于机器字节顺序。
杰夫·沃克

@JeffWalkerCodeRanger:来自Eric Lippert,年龄较早:blogs.msdn.com/b/ericlippert/archive/2004/05/25/141525.aspx
Ben Mosher

我看不到Eric Lippert链接如何回答这个问题。在github.com/mono/mono/blob/master/mcs/class/corlib/System/上查看Mono代码……在我看来,他们总是假设字节以小尾数顺序出现,而不管本机尾数如何。这符合我的理解,即如果它依赖于平台,它将与MS api或规范的语义不匹配。查看反汇编的mscorelib,似乎还假设数组中的字节也按小端顺序排列。
杰夫·沃克

看起来你是对的。内部存储格式对字节序敏感,而构造函数和ToByteArray则不然。他们总是lil'-endian。编辑输入。
Ben Mosher 2013年

3

这是客户端的“顺序引导”解决方案。

http://www.pinvoke.net/default.aspx/rpcrt4.uuidcreate

using System;
using System.Runtime.InteropServices;


namespace MyCompany.MyTechnology.Framework.CrossDomain.GuidExtend
{
    public static class Guid
    {

        /*

        Original Reference for Code:
        http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html

        */


        [DllImport("rpcrt4.dll", SetLastError = true)]
        static extern int UuidCreateSequential(out System.Guid guid);

        public static System.Guid NewGuid()
        {
            return CreateSequentialUuid();
        }


        public static System.Guid CreateSequentialUuid()
        {
            const int RPC_S_OK = 0;
            System.Guid g;
            int hr = UuidCreateSequential(out g);
            if (hr != RPC_S_OK)
                throw new ApplicationException("UuidCreateSequential failed: " + hr);
            return g;
        }


        /*

        Text From URL above:

        UuidCreateSequential (rpcrt4)

        Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
        To create a page in a module other than rpcrt4, prefix the name with the module name and a period.
        . Summary
        Creates a new UUID 
        C# Signature:
        [DllImport("rpcrt4.dll", SetLastError=true)]
        static extern int UuidCreateSequential(out Guid guid);


        VB Signature:
        Declare Function UuidCreateSequential Lib "rpcrt4.dll" (ByRef id As Guid) As Integer


        User-Defined Types:
        None.

        Notes:
        Microsoft changed the UuidCreate function so it no longer uses the machine's MAC address as part of the UUID. Since CoCreateGuid calls UuidCreate to get its GUID, its output also changed. If you still like the GUIDs to be generated in sequential order (helpful for keeping a related group of GUIDs together in the system registry), you can use the UuidCreateSequential function.

        CoCreateGuid generates random-looking GUIDs like these:

        92E60A8A-2A99-4F53-9A71-AC69BD7E4D75
        BB88FD63-DAC2-4B15-8ADF-1D502E64B92F
        28F8800C-C804-4F0F-B6F1-24BFC4D4EE80
        EBD133A6-6CF3-4ADA-B723-A8177B70D268
        B10A35C0-F012-4EC1-9D24-3CC91D2B7122



        UuidCreateSequential generates sequential GUIDs like these:

        19F287B4-8830-11D9-8BFC-000CF1ADC5B7
        19F287B5-8830-11D9-8BFC-000CF1ADC5B7
        19F287B6-8830-11D9-8BFC-000CF1ADC5B7
        19F287B7-8830-11D9-8BFC-000CF1ADC5B7
        19F287B8-8830-11D9-8BFC-000CF1ADC5B7



        Here is a summary of the differences in the output of UuidCreateSequential:

        The last six bytes reveal your MAC address 
        Several GUIDs generated in a row are sequential 
        Tips & Tricks:
        Please add some!

        Sample Code in C#:
        static Guid UuidCreateSequential()
        {
           const int RPC_S_OK = 0;
           Guid g;
           int hr = UuidCreateSequential(out g);
           if (hr != RPC_S_OK)
             throw new ApplicationException
               ("UuidCreateSequential failed: " + hr);
           return g;
        }



        Sample Code in VB:
        Sub Main()
           Dim myId As Guid
           Dim code As Integer
           code = UuidCreateSequential(myId)
           If code <> 0 Then
             Console.WriteLine("UuidCreateSequential failed: {0}", code)
           Else
             Console.WriteLine(myId)
           End If
        End Sub




        */








    }
}

关键字:CreateSequentialUUID SequentialUUID



By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.