Learning never exhausts the mind
Home >  Coding > C# ASP.Net MVC > Generate a Random Strings of Characters with C#

Last Updated on by

Generate random strings of a given length containing either upper case or lower case letters with this short snippet.

This copy and paste function allows you to quickly generate random strings with C# and can be used for random identifiers, codes, semi-secure passwords and anywhere else where you may require a random string to be used.

The chosen strings are not completely random because a mathematical algorithm is used to select them, but they are sufficiently random for practical purposes. The current implementation of the Random class is based on Donald E. Knuth's subtractive random number generator algorithm. To generate a cryptographically secure random number, such as the one that's suitable for creating a random password, use the RNGCryptoServiceProvider class.

Random Strings Function

/// <summary>
/// Generates random strings with a given length
/// </summary>
/// <param name="size">Size of the string</param>
/// <param name="lowerCase">If true, generate lowercase string</param>
/// <returns>Random string</returns>
private string RandomString(int size, bool lowerCase)
{
  StringBuilder builder = new StringBuilder();
  Random random = new Random();
  char ch;
  for (int i = 1; i < size+1; i++)
  {
    ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
    builder.Append(ch);
  }
  if (lowerCase)
    return builder.ToString().ToLower();
  else
    return builder.ToString();
}

You may also like to try our lorem ipsum generator for random words and paragraphs.

One thought on “Generate a Random Strings of Characters with C#
  • 18th July 2014 at 12:00 am

    private string RandomString(int size)
    {
    var random = new Random();
    Func generator = _=>(char)(int)Math.Floor('Z'-'A' * random.NextDouble() + 'A');
    return string.Join("", Enumerable.Range(1, size).Select(generator));
    }

    Reply

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.