If you’ve ever wanted to generate some random strings, here is a piece of code that can be helpful at times. Note that you can supply any other content for the array to choose the new string’s characters from.
private string GenerateRandomString(int length)
{
Char[] allowedChars = GetPrintableCharacters();
char[] chars = new char[length];
var rd = new Random();
for (int i = 0; i < length; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}
private Char[] GetPrintableCharacters()
{
List<Char> printableChars = new List<char>();
for (int i = char.MinValue; i <= char.MaxValue; i++)
{
char c = Convert.ToChar(i);
if (!char.IsControl(c))
{
printableChars.Add(c);
}
}
return printableChars.ToArray();
}