How can I generate a random 8 character alphanumeric string in C#?
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
Not as elegant as the Linq solution.
(Note: The use of the Random
class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider
class if you need a strong random number generator.)