Tuesday 20 December 2011

How to generate random password in Asp.Net / C#.Net?

Definition: Generate Random Password.

Code:
private string GeneratePassword(byte Length)
    {
        char[] Chars = new char[] {
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
        };
        string String = string.Empty;
        Random Random = new Random();

        for (byte a = 0; a < Length; a++)
        {
            String += Chars[Random.Next(0, 61)];
        };

        return (String);
    }

How to call GeneratePassword method?

string pwd = string.Empty;
//generate random password
pwd = GeneratePwd(8);  //we have to pass length of password. you can pass any length


No comments:

Post a Comment