How to Generate a New Guid

C# how to create a Guid value?

Guid id = Guid.NewGuid();

How to generate a Guid in SQL Server?

This will generate a Guid in SQL Server:

SELECT NEWID()

Guid.NewGuid() vs. new Guid()

new Guid() makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).

Guid.NewGuid() makes an actual guid with a unique value, what you probably want.

How do I create a GUID / UUID?

UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to RFC 4122, are identifiers designed to provide certain uniqueness guarantees.

While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see @broofa's answer, below) there are several common pitfalls:

  • Invalid id format (UUIDs must be of the form "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx", where x is one of [0-9, a-f] M is one of [1-5], and N is [8, 9, a, or b]
  • Use of a low-quality source of randomness (such as Math.random)

Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the uuid module.

Generating a plain GUID in Visual Studio

You can use the following command (language C#) for my Visual Commander extension to insert a plain GUID:

public class C : VisualCommanderExt.ICommand
{
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
EnvDTE.TextSelection ts = DTE.ActiveDocument.Selection as EnvDTE.TextSelection;
ts.Text = System.Guid.NewGuid().ToString();
}
}

How to generate a new GUID?

You can try the following:

function GUID()
{
if (function_exists('com_create_guid') === true)
{
return trim(com_create_guid(), '{}');
}

return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

Source - com_create_guid

How to generate absolutely unique GUID's?

Sure. A GUID is just a 128-bit value. So use a 128-bit integer (e.g. represented by two ulong values) and increment it. When you've reached the maximum value for the 128-bit integer type, you've generated all possible GUIDs. For example:

public IEnumerable<Guid> GetAllGuids()
{
unchecked
{
byte[] buffer = new byte[16];
ulong x = 0UL;
do
{
byte[] high = BitConverter.GetBytes(x);
Array.Copy(high, 0, buffer, 0, 8);
ulong y = 0UL;
do
{
y++;
byte[] low = BitConverter.GetBytes(y);
Array.Copy(low, 0, buffer, 8, 8);
yield return new Guid(buffer);
} while (y != 0UL);
x++;
} while (x != 0UL);
}
}

Notes:

  • This is definitely not as efficient as it might be.
  • Iterating over all possible ulong values is a pain - I don't like using do...while...
  • As noted in comments, this will produce values which are not valid UUIDs

Of course, this is in no way random...

In practice, as others have mentioned, the chances of collisions from Guid.NewGuid are incredibly small.

How do I generate a new GUID and then write to a new file in a specified path, using that GUID as the filename?

Something like this

var somepath = Path.GetTempPath(); // tempFolder if you want it
var fileName = Path.Combine(somepath,$"{Guid.NewGuid()}.dat");

// Do something with your file name

Add pepper and salt to taste


Additional resources

Path.Combine Method

Combines strings into a path.

Guid.NewGuid Method

Initializes a new instance of the Guid structure.

Example

public static void Main()
{
Guid g;
// Create and display the value of two GUIDs.
g = Guid.NewGuid();
Console.WriteLine(g);
Console.WriteLine(Guid.NewGuid());
}

Output

0f8fad5b-d9cb-469f-a165-70867728950e
7c9e6679-7425-40de-944b-e07fc1f90ae7

Create a GUID in Java

Have a look at the UUID class bundled with Java 5 and later.

For example:

  • If you want a random UUID you can use the randomUUID method.
  • If you want a UUID initialized to a specific value you can use the UUID constructor or the fromString method.

How to generate guid from DateTime?

If the goal is to get reproducible GUIDs, then you need to disable the random components. These are set when the program starts. After that they no longer change, so the generated GUIDs are stable from then on, but each run of the program will use different random values, so each run will give a different semi-random GUID for a known datetime value.

To disable it, simply do:

//var random = new Random();
//random.NextBytes(DefaultClockSequence);
//random.NextBytes(DefaultNode);

Furthermore when running it locally, you have to force your DateTime value to use UTC, which I did as follows:

DateTime dateTimeFromGuid = GuidGenerator.GetDateTime(gui);
dateTimeFromGuid = new DateTime(dateTimeFromGuid.Ticks, DateTimeKind.Utc);

It would be much better to move this "UTC fix" into the library code.

Fiddle (I also changed the input GUID to a "non-randomized" value):

https://dotnetfiddle.net/niIHlz



Related Topics



Leave a reply



Submit