Introduction
Generating password is not a big deal. Pool the character from the character array and you will be generating password easily. This example shows how easily you can dynamically generate a password.Background
Using the code
PWDGenerator.cs uses System.Collections namespace to apply ArrayList. You can set the length of the password by setting the passwordlength to the length as you need.
This example simply demonstrate the basic use of Arraylist and Random number to generate random combinations or alphabets and numbers.
public static string GeneratePWD()
{
int passwordLength = 10;
int quantity = 1;
ArrayList arrCharPool = new ArrayList();
Random rndNum = new Random();
arrCharPool.Clear();
string password = "";
//Lower Case
for (int i = 97; i < 123; i++)
{
arrCharPool.Add(Convert.ToChar(i).ToString());
}
//Number
for (int i = 48; i < 58; i++)
{
arrCharPool.Add(Convert.ToChar(i).ToString());
}
//Upper Case
for (int i = 65; i < 91; i++)
{
arrCharPool.Add(Convert.ToChar(i).ToString());
}
for (int x = 0; x < quantity; x++)
{
//Iterate through the number of characters required in the password
for (int i = 0; i < passwordLength; i++)
{
password += arrCharPool[rndNum.Next(arrCharPool.Count)].ToString();
}
}
return password;
}
Build the application and start clicking the generate button. Instantly you will notice the changes. Here what I have done is selecting the integer values and converting them in the character which I have added to ArrayList and finally iterated through the generated characters from the ArrayList and generated a string of the specified length.
This example is simple and definitely you are going to enjoy by using it in your application.
History
- Initial release - 9th June 2008.
Conclusion
From this article we can simply generate an algorithm to generate random strings in the format as we have designed. Suppose you want to generate a password in more redable form for the new users signed up in your application or website and you need to send them password, then in that case you can simply use the ramdom strings generated from the above application as a password to the new users.