In this article, we will learn how to generate a random alphanumeric string in C#. Random String is sometimes needed. So you can generate a random alphanumeric string of a given length by using this code snippet. This function allows you to quickly generate a random string 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.
Here is the code to Generate Alphanumeric Random String.
using System;
using System.Linq;
namespace Tutorialsrack
{
class Program
{
/*How to Generate Random AlphaNumeric String in C#*/
static void Main(string[] args)
{
Console.WriteLine("Random AlphaNumeric String is {0}", GenerateRandomAlphaNumericString(8));
Console.ReadKey();
}
public static string GenerateRandomAlphaNumericString(int length)
{
//Characters used in for Generating AlphaNumeric String
var chars = "0123456789qazwsxedcrfvtgbyhnujmiklopQAZWSXEDCRFVTGBYHNUJMIKLOP@_$";
var random = new Random();
var Result = new string(
Enumerable.Repeat(chars, length) //Here "length" is the length of the alphaNumeric String
.Select(s => s[random.Next(s.Length)])
.ToArray());
return Convert.ToString(Result);
}
}
}
Random AlphaNumeric String is wIqjEDZ0
Random AlphaNumeric String is WPFKrllb
I hope this article will help you to understand how to generate a random alphanumeric string in C#.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments