How to Create a Random Password Generator in C#

By FoxLearn 7/18/2024 7:50:44 AM   9.19K
Creating a random password generator in a C# Windows Forms Application involves generating passwords with specified criteria such as length, character types (letters, digits, special characters), and complexity.

Sometimes you need to create default password, for example reset password, you can do it by following way.

How to Create a Random Password Generator in C#

Here’s a step-by-step guide to creating a basic random password generator:

C# password generator alphanumeric.

Drag and drop controls onto your form, then create a simple user interface allows you to generate random password with options lower case, upper case, numeric or specical character as shown below.

c# password generator

Next, Create a PasswordGenerator method allows you to generate password.

// random password c# generator
public string PasswordGenerator(bool lowerCase, bool upperCase, bool mumberic, bool specialCharacter, int length)
{
    char[] password = new char[length];
    string charSet = "";
    System.Random _random = new Random();
    if (lowerCase)
        charSet += LOWER_CASE;
    if (upperCase)
        charSet += UPPER_CASE;
    if (mumberic)
        charSet += NUMBERIC;
    if (specialCharacter)
        charSet += SPECIAL_CHARACTER;
    for (int i = 0; i < length; i++)
        password[i] = charSet[_random.Next(charSet.Length - 1)];
    return string.Join(null, password);
}

Each option is selected we will concatenate, then generate random string in c#.

const string LOWER_CASE = "abcdefghijklmnopqursuvwxyz";
const string UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string NUMBERIC = "1234567890";
const string SPECIAL_CHARACTER = @"~!@#$%^&*()+=-";

Adding a click event handler to the Generate button allows you to generate password.

//c# text generator
private void btnGenerate_Click(object sender, EventArgs e)
{
    try
    {
        txtPassword.Text = PasswordGenerator(chkLowerCase.Checked, chkUpperCase.Checked, chkNumeric.Checked, chkSpecical.Checked, int.Parse(txtPasswordLength.Text));
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Hit F5 to run your application and test your random password generator. You can easily choose how to create a password that combines lower case letters, upper case letters, numbers, or special characters.