Chris Rasmussen · Photographer · Infrastructure Guy · Code Dabbler · Traveller

C# – Generate Random String

While writing a web app recently that needed to get new members to confirm their email address, I had to do the normal thing where the members had to click a link sent to them via email. This process usually includes a randomly-generated string in the URL’s querystring. There are other methods such as CaptchaImage but I’ll cover those in another post.

For this situation I chose to generate a string 4 characters in length, generated at run-time. This is done with a small function I found that looks like the following.

private string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (lowerCase)
{
return builder.ToString().ToLower();
return builder.ToString();
}
}

You can use this function as part of a button click if you want, or, as in this case, as part of the Page_Load method. Once you’ve added the RandomString method to your application the simplest example of using the Page_Load method to show the results of the RandomString method would be the following code. This assumes you want the string to be 4 characters long and all lower-case.

protected void Page_Load(object sender, EventArgs e)
{
Response.Write(RandomString(4, true));
}

This function was found in this article at C# Corner.

banner ad

One Response to “C# – Generate Random String”

  1. Saiful says:

    Its good. Thanks.

Leave a Reply

Powered by Wordpress | Designed by Elegant Themes