Created
May 9, 2012 22:27
-
-
Save xpando/2649370 to your computer and use it in GitHub Desktop.
Generate random string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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