Friday, April 02, 2010

C# – Generate a random string

Generating a random string is useful for unit tests (filling your objects with random garbage). Here is a simple snippet to generate random strings/number/symbols in any combination. Useful for suggesting passwords.

static Random random = new Random(DateTime.Now.Second);
private static string PASSWORD_CHARS_LCASE = "abcdefghijklmnopqrstuvwxyz";
private static string PASSWORD_CHARS_NUMERIC = "0123456789";
private static string PASSWORD_CHARS_SPECIAL = "*$-+?_&=!%{}/";
public static string RandomString(int size, bool allowNumbers, bool allowUpperCase, bool allowLowerCase, bool allowSpecialChars)
{
StringBuilder builder = new StringBuilder();

List<char> validCharList = new List<char>();
if (allowNumbers)
validCharList.AddRange(PASSWORD_CHARS_NUMERIC.ToCharArray());
if (allowLowerCase)
validCharList.AddRange(PASSWORD_CHARS_LCASE.ToCharArray());
if (allowUpperCase)
validCharList.AddRange(PASSWORD_CHARS_LCASE.ToUpper().ToCharArray());
if (allowSpecialChars)
validCharList.AddRange(PASSWORD_CHARS_SPECIAL.ToCharArray());

while (builder.Length < size)
{
builder.Append(validCharList[random.Next(0, validCharList.Count)]);
}

return builder.ToString();
}

2 comments:

Anonymous said...

Passing bool to methods never a good idea.

Anthony D. Leatherwood said...
This comment has been removed by the author.