EN
C# / .NET - generate random string (random text)
5
points
In C# / .NET it is possible to generate random text in few ways.
1. Random
string
example
public static class RandomUtils
{
private static readonly string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789";
public static string generateText(int length)
{
Random random = new Random();
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; ++i)
{
int index = random.Next(ALPHABET.Length);
builder.Append(ALPHABET[index]);
}
return builder.ToString();
}
}
Example:
string value = RandomUtils.generateText(32);
Console.WriteLine(value);
Output:
inog93o8FXgBSy5kgali4RjF0JRUeMUf
2. Random
characters example
public static class RandomUtils
{
private static readonly string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789";
public static char[] generateChars(int length)
{
Random random = new Random();
char[] result = new char[length];
for (int i = 0; i < length; ++i)
{
int index = random.Next(ALPHABET.Length);
result[i] = ALPHABET[index];
}
return result;
}
}
Example:
char[] value = RandomUtils.generateChars(32);
Console.WriteLine(value);
Output:
atKK7quegNmtzHuKLK57kaVenhzsSCiA