Tuesday, December 4, 2012

Generate Random Password in C#.NET


Generating a random password becomes important in a application when the user wants to reset his/her  password. We can write a method which generate a password with a given length and using numbers, Letters or special characters.

Random type in C# performs the basic process of generating a random string.


The Random type is a class in the base class library. It is available in programs that include the System namespace.

private void GeneratePassword()
    {
        string strPwdchar = "abcdefghijklmnopqrstuvwxyz0123456789#+@&$ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string strPwd = "";
        Random rnd = new Random();
        for (int i = 0; i <= 7; i++)// Will generate a password with 8 characters
        {
            int iRandom = rnd.Next(0, strPwdchar.Length - 1);
            strPwd += strPwdchar.Substring(iRandom, 1);//Parameters are start index,length
        }
        Response.Write(strPwd);
    }

OutPut:
gwxH4jk& 

No comments:
Write comments
Recommended Posts × +