Web Design that taps into the haromny and vision of your dreams.

Generate a Random Strings of Characters with C#

By on in Coding

215 words, estimated reading time 1 minutes.

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.

Last updated on: Thursday 9th August 2018

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

Jozef

Jozef

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 to Jozef

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.