How To Create Random Password Of Given Length Using C#

Here I have written the code to create random Password/Number using uppercase, lowercase, digits, and special characters.

.Net provides the class Random , which has three methods - Next, NextBytes, and NextDouble.
  • Next()- Next method returns a random number.
  • NextBytes()-NextBytes returns an array of bytes filled with random numbers.
  • NextDouble()- returns a random number between 0.0 and 1.0.
I have used NextDouble.

Use

We can use this random password for One Time Password (OTP) or Temporary Password.

Code written in Console Application
  1. //Libraries  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. namespace PasswordPractice {  
  8.     class PasswordCreate {  
  9.         //Tis function is making the Random Password  
  10.         public string makeRandomPassword(int length) {  
  11.             string UpperCase = "QWERTYUIOPASDFGHJKLZXCVBNM";  
  12.             string LowerCase = "qwertyuiopasdfghjklzxcvbnm";  
  13.             string Digits = "1234567890";  
  14.             string allCharacters = UpperCase + LowerCase + Digits;  
  15.             //Random will give random charactors for given length  
  16.             Random r = new Random();  
  17.             String password = "";  
  18.             for (int i = 0; i < length; i++) {  
  19.                 double rand = r.NextDouble();  
  20.                 if (i == 0) {  
  21.                     password += UpperCase.ToCharArray()[(int) Math.Floor(rand * UpperCase.Length)];  
  22.                 } else {  
  23.                     password += allCharacters.ToCharArray()[(int) Math.Floor(rand * allCharacters.Length)];  
  24.                 }  
  25.             }  
  26.             Console.WriteLine(password);  
  27.             Console.ReadLine();  
  28.             return password;  
  29.         }  
  30.         static void Main(string[] args) {  
  31.             //User Input  
  32.             Console.WriteLine("Enter length of password");  
  33.             string len = Console.ReadLine();  
  34.             PasswordCreate n = new PasswordCreate();  
  35.             //Call the method in main method  
  36.             n.makeRandomPassword(Convert.ToInt32(len));  
  37.         }  
  38.     }  
  39. }  
Output of Given Code



I have uploaded the same as an attachment. Please download and make changes accordingly.