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

Generate a Random Strings of Characters with C#

Random strings generator for passwords, codes, and identifiers

Written By on in C#

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: Wednesday 21st June 2017

 

Comments
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

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me