How to generate random password in asp.net?



Hi
So many time, we will get requirement to send the random password to the users in asp.net project.

Here is the simple code to do this task
step1: Create one class in app_code file and write this method there

public static string GetRandomPassword(int length)
{
char[] chars = “$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&”.ToCharArray();
string password = string.Empty;
Random random = new Random();

for (int i = 0; i < length; i++)
{
int x = random.Next(1, chars.Length);
//For avoiding Repetation of Characters
if (!password.Contains(chars.GetValue(x).ToString()))
password += chars.GetValue(x);
else
i–;
}
return password;
}

Step2: Call the method in asp.net page like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

Label1.Text = PasswordGeneration.GetRandomPassword(10).ToString();

}
}

Advertisements

2 Responses to “How to generate random password in asp.net?”

  1. Santosh Joshi Says:

    Dear Chandradev,
    This is a normal requirement in web application but no one has done this job before.Good job man.

    • Chandra Dev Says:

      Hi Santosh
      Thank you for your valuable comment. If you want any help regarding coding then let me know.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: