How to Create a Random Password Generator in C#
By FoxLearn 7/18/2024 7:50:44 AM 9.44K
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.
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.
- How to update UI from another thread in C#
- How to get CheckedListBox selected values in C#
- How to use Advanced Filter DataGridView in C#
- How to create a Notification Popup in C#
- How to Use Form Load and Button click Event in C#
- How to Link Chart /Graph with Database in C#
- How to Check SQL Server Connection in C#
- How to Generate Serial Key in C#