Details

Random Character Generator

Generate random characters

public static class RandomCharacterGenerator
{
   private static readonly Random _random = new();
   
   public static string GenerateRandomPassword(int length = 12)
   {
       if (length < 8)
       {
           throw new ArgumentException("Password length should be at least 8 characters.");
       }
       
       const string upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
       const string lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
       const string digits = "0123456789";
       const string specialCharacters = "!@#$%^&*()-_=+[]{}|;:,.<>?";
       
       // Ensure that the password has at least one of each type of character
       var passwordBuilder = new StringBuilder();
       passwordBuilder.Append(upperCaseLetters[_random.Next(upperCaseLetters.Length)]);
       passwordBuilder.Append(lowerCaseLetters[_random.Next(lowerCaseLetters.Length)]);
       passwordBuilder.Append(digits[_random.Next(digits.Length)]);
       passwordBuilder.Append(specialCharacters[_random.Next(specialCharacters.Length)]);
       
       // Fill the remaining length with random characters from all groups
       string allCharacters = upperCaseLetters + lowerCaseLetters + digits + specialCharacters;
       
       for (int i = 4; i < length; i++)
       {
           passwordBuilder.Append(allCharacters[_random.Next(allCharacters.Length)]);
       }
       
       // Shuffle the password to ensure randomness
       return new string(passwordBuilder.ToString().OrderBy(_ => _random.Next()).ToArray());
   }
}

Can be used to generate other stuff too!