Skip to content

Instantly share code, notes, and snippets.

@xpando
Created May 9, 2012 22:27
Show Gist options
  • Save xpando/2649370 to your computer and use it in GitHub Desktop.
Save xpando/2649370 to your computer and use it in GitHub Desktop.
Generate random string
public static class StringExtensions
{
// Generates a random seq of characters
// e.g. "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ01234567890!@#$%&*()-+".Randomize(8);
public static string Randomize(this string characters, int len)
{
var rng = new RNGCryptoServiceProvider();
var builder = new StringBuilder(len);
var bytes = new byte[4];
for (var i = 0; i < len; i++)
{
rng.GetBytes(bytes);
var idx = Math.Abs(BitConverter.ToInt32(bytes, 0)) % characters.Length;
builder.Append(characters[idx]);
}
return builder.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment