Friday, August 20, 2010

Generate Alphanumeric Password in .NET

using System;

public partial class generatePassword : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {   //Set the length of password
        int length = 9;
        string strPassword=generateNewPassword(length);
        Response.Write(strPassword);
    }

    private string generateNewPassword(int length)
    {
        string strPassword=string.Empty;
        //Include all the character in the array which you want to include in the password
        string[] strPwdCharArrar = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "!", "@", "#", "$", "%", "&", "*", "(", ")", "+", "=", "-", "/", "~" };
        int intArrayLen = strPwdCharArrar.Length;
        Random objRan = new Random();
        for (int i = 1; i <= length; i++)
        {   //Pick that character from the array randomly        
            int intNextPlace = objRan.Next(0, intArrayLen - 1);
            strPassword += strPwdCharArrar.GetValue(intNextPlace).ToString();
        }
        objRan = null;
        return strPassword;
    }
}

No comments:

Post a Comment