create a password with a custom length and symbols in csharp

To create a password with a custom length and symbols in C#, you can generate secure random characters using cryptography. Here is an example code snippet to generate a password with a custom length of 12 characters, including at least one uppercase letter, one lowercase letter, and one symbol:

main.cs
using System;
using System.Security.Cryptography;
using System.Text;

public static string GeneratePassword(int length)
{
    const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()-_=+\\|[{]};:'\",<.>/?";
    var chars = new char[length];
    var random = new RNGCryptoServiceProvider();

    for (int i = 0; i < length; i++)
    {
        byte[] bytes = new byte[1];
        do
        {
            random.GetBytes(bytes);
        }
        while (bytes[0] > validChars.Length);

        chars[i] = validChars[bytes[0]];
    }

    return new string(chars);
}
607 chars
25 lines

You can call this method with the desired length parameter to generate a unique secure password.

gistlibby LogSnag