Last active
September 11, 2015 10:42
-
-
Save SecretDeveloper/5351a9071f6b5f2eb8dc 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 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