How to generate random password in asp.net c#

In this article, many time we need to set random password for the registration.so I have written this post for that. In this post , I have shown this random password on label , you can show according your requirement .

Source code:-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="generaterandompwd.aspx.cs" Inherits="generaterandompwd" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Label ID="lbpassword" runat="server" Text=""></asp:Label>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"  Text="Generate" />
   
    </div>
    </form>
</body>
</html>


Password:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

       
       
    }

    public static string CreateRandomPassword(int PasswordLength)
    {
        string _allowedChars = "@#*&^%0123456789abcdefghijkmnopqrstuvwxyz+)(_-?><ABCDEFGHJKLMNOPQRSTUVWXYZ";
        Random randNum = new Random();
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;
        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
        }
        return new string(chars);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        lbpassword.Text = CreateRandomPassword(9).ToString();
    }
}

Out-put:-


How to generate random password in asp.net c# How to generate random password in asp.net c# Reviewed by NEERAJ SRIVASTAVA on 6:04:00 PM Rating: 5

No comments:

Powered by Blogger.