How to Generate Uuid in C#

How can I generate UUID in C#

You are probably looking for System.Guid.NewGuid().

Generate a unique id

Why not just use ToString?

public string generateID()
{
return Guid.NewGuid().ToString("N");
}

If you would like it to be based on a URL, you could simply do the following:

public string generateID(string sourceUrl)
{
return string.Format("{0}_{1:N}", sourceUrl, Guid.NewGuid());
}

If you want to hide the URL, you could use some form of SHA1 on the sourceURL, but I'm not sure what that might achieve.

How to generate UUID version 4 using c#

GUIDs are V4... every single GUID you generate will look like this

18acac20-991e-437e-9529-a441452f6b7e
d6d68639-64c2-452e-95b7-16cf6dbf5301
b0943b6d-4779-4771-92bf-cc2d634fb671
218b5620-d30d-46d9-9c88-38a4ac64266e
de03042c-792f-4689-80ca-26287ceb2129
1175bb5d-d35e-4a46-aaac-0825c749dc3a
42864583-c0f6-4e44-8710-39c9a9146d43
223ca924-4b77-4931-bb94-c1d371894683
2c4495ab-19e4-4aeb-b647-10db8625791c
f5894345-cbe3-4fc7-92c3-d6d863f70411
^ ^
1 2

The digit at position 1 above is always 4 and the digit at position 2 is always one of 8, 9, A or B.

You can confirm this by

var cts = new CancellationTokenSource();

var parallelOptions = new ParallelOptions() { MaxDegreeOfParallelism = 8, CancellationToken = cts.Token };
Parallel.For(0, int.MaxValue, parallelOptions, (i) =>
{
var guid = Guid.NewGuid().ToString();
var four = guid.ElementAt(14);
var ab89 = guid.ElementAt(19);

if (four != '4') cts.Cancel();
if (ab89 != 'a' && ab89 != 'b' && ab89 != '8' && ab89 != '9') cts.Cancel();

if ((i % 100000) == 0 && i < (int.MaxValue / 8))
{
Console.WriteLine($"{i * 8:n}"); // roughly
}
});

That will run through 4billion'ish attempts in a reasonable amount of time if you have doubts

Generating UUID based on strings

No, what you propose is not valid because it fundamentally breaks how UUIDs work. Use a real UUID for your namespace.

A convenient (and valid) way to accomplish this is hierarchical namespaces. First, use the standard DNS namespace UUID plus your domain name to generate your root namespace:

Guid nsDNS = new Guid("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
Guid nsRoot = Guid.Create(nsDNS, "myapp.example.com", 5);

Then create a namespace UUID for your string:

Guid nsFoo = Guid.Create(nsRoot, "Foo", 5);

Now you're ready to use your new Foo namespace UUID with individual names:

Guid bar = Guid.Create(nsFoo, "Bar", 5);

The benefit of this is that anyone else will get completely different UUIDs than you, even if their strings (other than the domain, obviously) are identical to yours, preventing collisions if your data sets are ever merged, yet it's completely deterministic, logical and self-documenting.

(Note: I've never actually used C#, so if I got the syntax slightly wrong, feel free to edit. I think the pattern is clear regardless.)

UUID interop with c# code

If all you need is the same UUID string (and not actual UUID/Guid objects), this C# method will return the same value as Java's UUID.nameUUIDFromBytes(byte[]) method.

public static string NameUUIDFromBytes(byte[] input)
{
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(input);
hash[6] &= 0x0f;
hash[6] |= 0x30;
hash[8] &= 0x3f;
hash[8] |= 0x80;
string hex = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
return hex.Insert(8, "-").Insert(13, "-").Insert(18, "-").Insert(23, "-");
}

C# Example

string test = "test";
Console.Out.WriteLine(NameUUIDFromBytes(Encoding.UTF8.GetBytes(test)));

Output:
098f6bcd-4621-3373-8ade-4e832627b4f6

Java Example

UUID test = UUID.nameUUIDFromBytes("test".getBytes("UTF-8"));
System.out.println(test);

Output:
098f6bcd-4621-3373-8ade-4e832627b4f6

Edit: I know it's after the fact, but this will produce an actual Guid object with the same value. Just incase anyone wants it.

public static Guid NameGuidFromBytes(byte[] input)
{
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(input);
hash[6] &= 0x0f;
hash[6] |= 0x30;
hash[8] &= 0x3f;
hash[8] |= 0x80;

byte temp = hash[6];
hash[6] = hash[7];
hash[7] = temp;

temp = hash[4];
hash[4] = hash[5];
hash[5] = temp;

temp = hash[0];
hash[0] = hash[3];
hash[3] = temp;

temp = hash[1];
hash[1] = hash[2];
hash[2] = temp;
return new Guid(hash);
}

C# how to create a Guid value?

Guid id = Guid.NewGuid();

how to get Device UUID using C#

You can apply a regular expression to filter the output from wmic:

private string GetUuid()
{
try
{
var proc = Process.Start(new ProcessStartInfo
{
FileName = "wmic.exe",
Arguments = "csproduct get uuid",
RedirectStandardOutput = true
});
if (proc != null)
{
string output = proc.StandardOutput.ReadToEnd();
// Search for UUID string
var match = System.Text.RegularExpressions.Regex.Match(output, @"[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}");
if (match.Success) { return match.Value; }
}
}
catch { } // Your exception handling
return null; // Or string.Empty
}

.NET Short Unique Identifier

This one a good one - http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx

and also here
YouTube-like GUID

You could use Base64:

string base64Guid = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

That generates a string like E1HKfn68Pkms5zsZsvKONw==. Since a GUID is
always 128 bits, you can omit the == that you know will always be
present at the end and that will give you a 22 character string. This
isn't as short as YouTube though.

How does C# generate GUIDs?

Original question:

How the Guid is generating it's identifier?? How will be it's output
if I use the following code Guid g = Guid.NewGuid();

Whether the output will be the combination of numbers and lettters or
the numbers alone will be there???

A .Net System.Guid is just a 128-bit integer (16 bytes). Numbers and letters have nothing to do with it. You can use the ToString() method to see various "human-readable" versions of a Guid, which include numbers 0-9 and letters A-F (representing hex values), but that's all up to you how you want to output it.



Related Topics



Leave a reply



Submit