Skip to content

Instantly share code, notes, and snippets.

@AydinAdn
Created March 24, 2023 13:31
Show Gist options
  • Save AydinAdn/cc9f68ff0876b162dc0650c4f12b2e77 to your computer and use it in GitHub Desktop.
Save AydinAdn/cc9f68ff0876b162dc0650c4f12b2e77 to your computer and use it in GitHub Desktop.
RandomStringGenerator
public static class RandomStringGenerator
{
private static readonly char[] defaultCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToArray();
public static string GenerateString(int length)
{
string text = "";
for (int i = 0; i < length; i++)
{
RandomNumberGenerator rNGCryptoServiceProvider = RandomNumberGenerator.Create();
byte[] array = new byte[1];
do
{
rNGCryptoServiceProvider.GetNonZeroBytes(array);
}
while (array[0] > 248);
text += defaultCharacters[(int)array[0] % defaultCharacters.Length];
}
return text;
}
public static string GenerateString(int length, char[] characters)
{
string text = "";
for (int i = 0; i < length; i++)
{
RandomNumberGenerator rNGCryptoServiceProvider = RandomNumberGenerator.Create();
byte[] array = new byte[1];
do
{
rNGCryptoServiceProvider.GetNonZeroBytes(array);
}
while (array[0] > 248);
text += characters[(int)array[0] % characters.Length];
}
return text;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment