Hi Ramanak,
Here's a quick algorithm to do want you want to do. Sorry it's not the cleanest but it works. Didn't have plenty of time to test it though.
You can change the minimum and maximum number of chars. You can also add other chars (symbols, etc) if you want. You can also make it cleaner, but don't create the Random object in the function or it will always generate the same password.
Again, sorry it's not the cleanest but I think you get the idea.
Have a good day.
Tomy
-
protected String RandomPassword()
-
{
-
String pwd = "";
-
int length = 0;
-
int index = 0;
-
int numericIndex = -1;
-
int upperCaseIndex = -1;
-
-
//Length of your password
-
length = rnd.Next(MINLENGTH, MAXLENGTH);
-
-
// You generate a password of the desired length
-
for (int i = 0; i < length; i++)
-
{
-
// Generate an index that smaller than the size of your allowed chars
-
index = rnd.Next(0, allowedChars.Length);
-
-
pwd += allowedChars[index];
-
}
-
-
////*********************************************************
-
// We make sure that there is at least one numeric
-
// Replace one random char by a numeric
-
numericIndex = rnd.Next(0, pwd.Length);
-
-
// Generate a numeric, delete one char and replace it with a numeric
-
index = rnd.Next(0, numericChars.Length);
-
pwd = pwd.Remove(numericIndex, 1);
-
pwd = pwd.Insert(numericIndex, numericChars[index].ToString());
-
////*********************************************************
-
-
-
////*********************************************************
-
// We make sure that there is at least one uppercase
-
// Replace one random char by a numeric
-
upperCaseIndex = rnd.Next(0, pwd.Length);
-
-
// We make sure our uppercase index is different
-
// from our numeric index or we will overwrite our
-
// only numeric value with our uppercase value
-
while (upperCaseIndex == numericIndex)
-
{
-
upperCaseIndex = rnd.Next(0, pwd.Length);
-
}
-
-
// Generate a numeric, delete one char and replace it with a numeric
-
index = rnd.Next(0, upperCaseChars.Length);
-
pwd = pwd.Remove(upperCaseIndex, 1);
-
pwd = pwd.Insert(upperCaseIndex, upperCaseChars[index].ToString());
-
////*********************************************************
-
-
return pwd;
-
}
-
-
Random rnd = new Random();
-
const int MINLENGTH = 6;
-
const int MAXLENGTH = 20;
-
const String allowedChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
const String upperCaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
const String numericChars = "0123456789";
-