Creating a Random Password

vishalneeraj-24503
Posted by vishalneeraj-24503 under C# category on | Points: 40 | Views : 587
For creating Random Password,we will use a combination of alpha-numeric password,we can use below code:-
public string CreateRandomPassword(int PasswordLength)
{
string allowedChars = "abcdefghijkmnpqrtuvwxyzACDEFHJKLMNPQRTUVWXY";
string allowedNums = "2345789";
Random randNum = new Random();
char[] chars = new char[PasswordLength];

bool flg = true;

for (int i = 0; i < PasswordLength; i++)
{
if (flg)
{
chars[i] = allowedChars[(int)((allowedChars.Length) * randNum.NextDouble())];
}
else
{
chars[i] = allowedNums[(int)((allowedNums.Length) * randNum.NextDouble())];
}

flg = !flg;
}

return new string(chars);
}

Response.Write("Random Password for length having 10->" + CreateRandomPassword(10) + "<br/>");
--> Will create Random password having 10 characters

Response.Write("Random Password for length having 2->" + CreateRandomPassword(2) + "<br/>");
--> Will create Random password having 2 characters

Response.Write("Random Password for length having 5->" + CreateRandomPassword(5) + "<br/>");
--> Will create Random password having 5 characters

Response.Write("Random Password for length having 7->" + CreateRandomPassword(7) + "<br/>");
--> Will create Random password having 7 characters

Comments or Responses

Login to post response