Generate a Random Number and a Random String in C#
csharpC# and .NETtipsrandomstrings
The Random class makes random numbers; it can be created with no value or with a seed. This helper builds a random string of a chosen length from letters, digits and special characters, optionally in capitals only.
// needs: using System; using System.Linq;
public static string GetRandomString(int length, bool includeAlphabet = true, bool includeNumbers = true,
bool includeSpecialChar = false, bool capsOnly = false)
{
Random ran = new Random();
string chars = "";
if (includeAlphabet)
chars += "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (includeNumbers)
chars += "1234567890";
if (includeSpecialChar)
chars += "!@#$%^&*()_";
string random = "";
for (int i = 0; i < length; i++)
{
int a = ran.Next(chars.Length);
random = random + chars.ElementAt(a);
}
return capsOnly ? random.ToUpper() : random;
}
Comments
Loading comments…