Random String Generation in C#

String generation method that get input as a length of the String you desired.
[code lang=”csharp”]
static Random rd = new Random();
[/code]
[code lang=”csharp”]
public static string CreateString(int stringLength)
{
const string allowedChars = "abcdefghijkmnopqrstuvwxyz0123456789";
char[] chars = new char[stringLength];

for (int i = 0; i < stringLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}

return new string(chars);
}
[/code]

Custom type defined string generator method.

[code lang=”csharp”]
public static string CreateString(int stringLength, int type)
{
string allowedChars = "";

if (type == 1)
{
allowedChars = "ABCDEFGHIJKMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
}
else if (type == 2)
{
allowedChars = "abcdefghijkmnopqrstuvwxyz0123456789";
}
else if (type == 3)
{
allowedChars = "0123456789";
}
else
{
allowedChars = "abcdefghijkmnopqrstuvwxyz0123456789";
}

char[] chars = new char[stringLength];

for (int i = 0; i < stringLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}

return new string(chars);
}
[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *