Skip to main content

A random password generator in C#.

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

public static string GenerateNewPassword(int lowercase, int uppercase, int numerics, int special)
{
    string lowers = "abcdefghijklmnopqrstuvwxyz";
    string uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string number = "0123456789";
    string specials = "~`!@#$%^&*()-_+={}[]|:;,.?";

    Random random = new Random();

    string generated = "";

    for (int i = 1; i <= lowercase; i++)
        generated = generated.Insert(
                        random.Next(generated.Length),
                        lowers[random.Next(lowers.Length - 1)].ToString()
                    );

    for (int i = 1; i <= uppercase; i++)
        generated = generated.Insert(
                        random.Next(generated.Length),
                        uppers[random.Next(uppers.Length - 1)].ToString()
                    );

    for (int i = 1; i <= numerics; i++)
        generated = generated.Insert(
                        random.Next(generated.Length),
                        number[random.Next(number.Length - 1)].ToString()
                    );

    for (int i = 1; i <= special; i++)
        generated = generated.Insert(
                        random.Next(generated.Length),
                        specials[random.Next(specials.Length - 1)].ToString()
                    );

    return generated;
}