generate random string with n characters in csharp

You can generate a random string of specified length in C# using the following code:

main.cs
public static string GenerateRandomString(int length)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
}
259 chars
7 lines

Here, we are first defining a string chars that includes all the possible characters that we want to include in our random string. Then, we are initializing a new instance of the Random class to generate random numbers.

Finally, we are using the Enumerable.Repeat() method to repeat the chars string length number of times, and then using the Select() method to randomly select a character from each of the repeated chars strings. We then convert this array of characters into a string using the String constructor.

To use this method, you can call it with the desired length of the random string:

main.cs
string randomString = GenerateRandomString(10);
48 chars
2 lines

This will generate a random string of length 10.

gistlibby LogSnag