How to Generate Random Password in asp.net Web-Forms
In this post, I am going to explain and demonstrate how to
generate Random Password in ASP.NET with c#.
Here are steps for that-
For this, We have
added a new page in our application then use the following code-
<%@ Page
Language="C#"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Generate Random Password</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<b>
Generate Random Password Using C#
</b></div>
</div>
<br />
<table class="style1">
<tr>
<td
class="style2">
Click On Button</td>
<td>
<asp:Button ID="BtnGenerateRandomPassword" runat="server"
Text="Generate"
Width="100px" Height="30px"
onclick="BtnGenerateRandomPassword_Click"
/>
</td>
</tr>
<tr>
<td
class="style3">
</td>
<td
class="style4">
<asp:Label ID="lblPassword"
runat="server"
Text=""></asp:Label>
</td>
</tr>
</table>
</form>
</body>
</html>
Default.aspx.cs Code
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)
{
}
protected void
BtnGenerateRandomPassword_Click(object sender, EventArgs e)
{
try
{
string allowedChars = "";
allowedChars = "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,";
allowedChars += "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,";
allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?";
char[] sep = { ','
};
string[] arr = allowedChars.Split(sep);
string passwordString = "";
string temp = "";
Random rand = new Random();
for (int i = 0; i
< 10; i++)
{
temp = arr[rand.Next(0, arr.Length)];
passwordString += temp;
}
lblPassword.Text = passwordString;
}
catch
{
throw;
}
}
}
Now run the application, we get the following screen where
we can Check whether the Random password generate or not. Here is the screen shots of the demo
application.
Download Source Code: Click Here
written by- Ravi Kumar Soni
nice
ReplyDelete