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.
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));
}