Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save IJsWorkshop/88b5dbd6cbe0ab4d07b6b2657dec15e3 to your computer and use it in GitHub Desktop.
Save IJsWorkshop/88b5dbd6cbe0ab4d07b6b2657dec15e3 to your computer and use it in GitHub Desktop.
cleaner way to generate a unique id
private static readonly RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
private string GenerateUniqueID(int length)
{
// We chose an encoding that fits 6 bits into every character,
// so we can fit length*6 bits in total.
// Each byte is 8 bits, so...
int sufficientBufferSizeInBytes = (length * 6 + 7) / 8;
var buffer = new byte[sufficientBufferSizeInBytes];
random.GetBytes(buffer);
return Convert.ToBase64String(buffer).Substring(0, length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment