Last active
June 23, 2021 09:30
-
-
Save guitarrapc/bc87cd62a71c059c0050df05b8ec9a23 to your computer and use it in GitHub Desktop.
Generate Random ascii string
This file contains hidden or 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
void Main() | |
{ | |
const string chars = "abcdefghijklmnopqrstuvwxyz0123456789"; | |
GenerateUniqueString(8, chars.ToCharArray()).Dump(); | |
} | |
public static string GenerateUniqueString(int size, char[] chars) | |
{ | |
var data = new byte[4 * size]; | |
using var crypto = new RNGCryptoServiceProvider(); | |
crypto.GetBytes(data); | |
var sb = new StringBuilder(size); | |
for (var i = 0; i < size; i++) | |
{ | |
var rnd = BitConverter.ToUInt32(data, i * 4); | |
var idx = rnd % chars.Length; | |
sb.Append(chars[idx]); | |
} | |
return sb.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sample