create a password with a custom length and uppercase letters in csharp

To create a password with a custom length and uppercase letters in C#, you can use a combination of random numbers and uppercase letters from the alphabet.

Here is an example code snippet that generates a password of custom length (in this case, 8 characters) with at least one uppercase letter:

main.cs
public string GeneratePassword(int length)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    string password = new string(
        Enumerable.Repeat(chars, length)
                  .Select(s => s[random.Next(s.Length)])
                  .ToArray());
    
    // Make sure there is at least one uppercase letter
    if (!password.Any(char.IsUpper))
    {
        // Replace a random character with a random uppercase letter
        var index = random.Next(0, length);
        password = password.Remove(index, 1)
                           .Insert(index, chars.Where(char.IsUpper).ElementAt(random.Next(0, 26)).ToString());
    }

    return password;
}
707 chars
21 lines

In this code, we are using the Random class to generate a sequence of random characters from a combination of uppercase letters and numbers. We then check if the generated password contains at least one uppercase letter. If it does not, we replace a random character in the password with a random uppercase letter to ensure that there is at least one uppercase letter in the password. The method returns the generated password as a string.

gistlibby LogSnag