How can I generate UUID in C#

前端 未结 5 633
不知归路
不知归路 2020-11-29 20:23

I am creating an .idl file programmatically. How do I create UUIDs for the interfaces and Methods Programmatically.

Can I generate the UUID programmatically?

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 20:33

    Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid parts.

    If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray() and encode it. You'll need to Array.Reverse the first three parts (Data1-3).

    I do it this way:

    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);
    

    See this answer for the specific .NET implementation details.

    Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray().

提交回复
热议问题