Thursday, May 22, 2014

Create random password in ASP.NET C#

In this tutorial I will show you how to make a random generate password in C#. You can apply it either in web application(ASP.NET) or in windows application.

Create a new project and add a web form or a win form as per your project. And then add a button. On the Button_Click() write the following code.

PasswordGenerator obj_p = new PasswordGenerator();
string new_password = obj_p.Generate();

Now you have to create a new class named PasswordGenerator and create a new method Generate.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace <Project_Name>
    public class PasswordGenerator
        public PasswordGenerator() { }
        /// <summary>
        /// Password generator method
        /// </summary>
        /// <returns></returns>
        public  string Generate()
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var stringChars = new char[8];
            var random = new Random();
            for (int i = 0; i < stringChars.Length; i++)
                stringChars[i] = chars[random.Next(chars.Length)];
            var finalString = new String(stringChars);
            return finalString.ToString();

Now run the project and get the new password in the string new_password.

Happy coading :)


Post a Comment

Follow by Email

Popular Posts