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
-
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace PasswordPractice {
- class PasswordCreate {
-
- public string makeRandomPassword(int length) {
- string UpperCase = "QWERTYUIOPASDFGHJKLZXCVBNM";
- string LowerCase = "qwertyuiopasdfghjklzxcvbnm";
- string Digits = "1234567890";
- string allCharacters = UpperCase + LowerCase + Digits;
-
- Random r = new Random();
- String password = "";
- for (int i = 0; i < length; i++) {
- double rand = r.NextDouble();
- if (i == 0) {
- password += UpperCase.ToCharArray()[(int) Math.Floor(rand * UpperCase.Length)];
- } else {
- password += allCharacters.ToCharArray()[(int) Math.Floor(rand * allCharacters.Length)];
- }
- }
- Console.WriteLine(password);
- Console.ReadLine();
- return password;
- }
- static void Main(string[] args) {
-
- Console.WriteLine("Enter length of password");
- string len = Console.ReadLine();
- PasswordCreate n = new PasswordCreate();
-
- n.makeRandomPassword(Convert.ToInt32(len));
- }
- }
- }
Output of Given Code
I have uploaded the same as an attachment. Please download and make changes accordingly.