I recently had to make a method that creates a random generated password in C#. So, I looked at the web for such a function and I found this one. It was really simple and short and just what I was looking for. But, there is always a but, it didn't work. So I modified it a bit, and it now looks like this and it works.

private static string CreateRandomPassword(int passwordLength)
{
 string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
 char[] chars = new char[passwordLength];
 Random rd = new Random();

 for (int i = 0; i < passwordLength; i++)
 {
  chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
 }

 return new string(chars);
}

It's that simple.

Comments

 wishy

it's great! can u explain every line? i want to understand every code. because i don't want to just copy it! i want to learn if u don't mind. tnx!

wishy
Bryan Canonica

This code can give you back strings with curse words in them. I would suggest using the code above modified a bit to alternate numerals and letters.

Bryan Canonica
Bryan Canonica

//Something like this builds on Mads Excellent code. public static string GenerateRandomString(int length) { //Removed O, o, 0, l, 1 string allowedLetterChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; string allowedNumberChars = "23456789"; char[] chars = new char[length]; Random rd = new Random(); bool useLetter = true; for (int i = 0; i &lt; length; i++) { if (useLetter) { chars[i] = allowedLetterChars[rd.Next(0, allowedLetterChars.Length)]; useLetter = false; } else { chars[i] = allowedNumberChars[rd.Next(0, allowedNumberChars.Length)]; useLetter = true; } } return new string(chars); }

Bryan Canonica

Comments are closed