Created
March 24, 2023 13:31
-
-
Save AydinAdn/cc9f68ff0876b162dc0650c4f12b2e77 to your computer and use it in GitHub Desktop.
RandomStringGenerator
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
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