[Solved] Random password generator c# with special characters

Strong password generator c#

Hey, Today I am going to show you how you can generate strong password with special characters in c#. Here we are taking a console application to do that

Random password generator c# with special characters

               Strong password generator c#

                                       How to upload image in gridview in asp.net using c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Random_password
    class Program
        static string alphaCaps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        static string alphaLow = "abcdefghijklmnopqrstuvwxyz";
        static string numerics = "1234567890";
        static string special = "@#$-=/";
        string allChars = alphaCaps + alphaLow + numerics + special;
        Random r = new Random();

        public string GenerateRandomStrongPassword(int length)
            String generatedPassword = "";
            if (length < 4)
                throw new Exception("Number of characters should be greater than 4.");
            int lowerpass, upperpass, numpass, specialchar;
            string posarray = "0123456789";
            if (length < posarray.Length)
            posarray = posarray.Substring(0, length);
            lowerpass = getRandomPosition(ref posarray);
            upperpass = getRandomPosition(ref posarray);
            numpass = getRandomPosition(ref posarray);
            specialchar = getRandomPosition(ref posarray);

            for (int i = 0; i < length; i++)
                if (i == lowerpass)
                    generatedPassword += getRandomChar(alphaCaps);
                else if (i == upperpass)
                    generatedPassword += getRandomChar(alphaLow);
                else if (i == numpass)
                    generatedPassword += getRandomChar(numerics);
                else if (i == specialchar)
                    generatedPassword += getRandomChar(special);
                    generatedPassword += getRandomChar(allChars);
            return generatedPassword;

        private string getRandomChar(string fullString)
            return fullString.ToCharArray()[(int)Math.Floor(r.NextDouble() * fullString.Length)].ToString();

        private int getRandomPosition(ref string posArray)
            int pos;
            string randomChar = posArray.ToCharArray()[(int)Math.Floor(r.NextDouble()* posArray.Length)].ToString();
            pos = int.Parse(randomChar);
            posArray = posArray.Replace(randomChar, "");
            return pos;
        //Calling the method 
        static void Main(string[] args)    //Main Method
            Program p = new Program();
            string rs = p.GenerateRandomStrongPassword(8);

Compile and run the program you will get the result. If you want to use it in your project then call the function and pass the password length in parameter()

How to upload image in gridview in asp.net using c#
How to perform insert and update operation on single button
Stored procedure to insert data into multiple tables in sql server

Read More

Generate random password in asp.net using c# and save in databse

Generate random password in asp.net using c# :-In this I going to show how to do registration and generate random password and save it in database. We will also send the mail to user's email for conformation of UserID and password.

This is very pretty step to generate random password of 8-digits, you can generate any digit of password depends on you. Alright let's get start.

How to generate random password in asp.net using c# and save in databse

Create table

      [id] [int] Primary key IDENTITY(1,1) NOT NULL,
      [username] [varchar](50) ,
      [email] [varchar](50) ,
      [password] [varchar](20)

First of all add the database connection within web.config file

    <add name="Mycon" connectionString="initial catalog =Test11718; data source=SANJAY\SQL2012; integrated security=true" providerName="System.Data.SqlClient"/>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>


Add a asp.net webform which name will be user-registration.aspx In this take two text-box one label and one button to save a record in database.

     Read More: How to upload image in gridview in asp.net using c#

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="user-registration.aspx.cs" Inherits="user_registration" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <form id="form1" runat="server">
                    <b>Send Password to Email and save it in database</b>
                    <td class="style1">Username:</td>
                        <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
                    <td class="style1">Email:</td>
                        <asp:TextBox ID="txt_Email" runat="server"></asp:TextBox>
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                     <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit"/>

Now come on the user-registration.aspx.cs   and add each and every necessary namespaces.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;

public partial class user_registration : System.Web.UI.Page
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    public static string CreateRandomPassword(int PasswordLength)
        string _allowedChars = "0123456789";
        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)
        string pwd = CreateRandomPassword(8);
        SqlCommand cmd = new SqlCommand("insert into employee(username,email,password) values (@username,@email,@password)", con);
        cmd.Parameters.AddWithValue("@username", txt_name.Text);
        cmd.Parameters.AddWithValue("@email", txt_Email.Text);
        cmd.Parameters.AddWithValue("@password", pwd);
        int i = cmd.ExecuteNonQuery();

    public void sendmail()
        SqlCommand cmd_cus = new SqlCommand("select email from employee where [email protected]", con);
        cmd_cus.Parameters.AddWithValue("@Email", txt_Email.Text);
        SqlDataReader dr = cmd_cus.ExecuteReader();
        if (dr.HasRows)
        string strNewPassword = CreateRandomPassword(8);
        string me = dr["email"].ToString();
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("[email protected]");
        msg.Subject = "Job Portal:Login Detail for your Account";
        msg.Body = "Your password is:-" + strNewPassword + "<br />" + "Your user name same as you email:- " + me;
        msg.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential("[email protected]m", "yourpassword");
        smtp.EnableSsl = true;
        lblMessage.Text = "Email Sent Successfully";
        lblMessage.ForeColor = System.Drawing.Color.ForestGreen;

In above tutorial I explained "how to generate random password in asp.net using c# and save in databse"  for the Gmail.com domain name. if you have another account like yahoo.com , outlook.com  then you may have to change port number and little bit code.

After done all these step , may you face a problem like this "Authentication the Server Response was 5.5.1 Authentication required in gmail" . In this case follow the given steps.

1. Login to your gmail account.
2. Visit this page https://accounts.google.com/DisplayUnlockCaptcha and click on button to allow access.
3. Visit this page https://www.google.com/settings/security/lesssecureapps and enable access for less secure apps.

Read our previous post

Read More