Skip to content

Instantly share code, notes, and snippets.

@SecretDeveloper
Last active September 11, 2015 10:42
Show Gist options
  • Save SecretDeveloper/5351a9071f6b5f2eb8dc to your computer and use it in GitHub Desktop.
Save SecretDeveloper/5351a9071f6b5f2eb8dc to your computer and use it in GitHub Desktop.
Generate Random String
public static string GenerateRandomString(int length = 32)
{
if (length <= 0)
throw new ArgumentException("provided length must be greater than 0");
using (RNGCryptoServiceProvider cryptoProvider = new RNGCryptoServiceProvider())
{
var bytes = new byte[length];
cryptoProvider.GetNonZeroBytes(bytes);
var allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890".ToCharArray();
var allowedLength = allowedChars.Length;
var buffer = new char[length];
for (int ndx = 0; ndx < length; ndx++)
{
buffer[ndx] = allowedChars[bytes[ndx] % allowedLength];
}
return new string(buffer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment