How can I generate random alphanumeric strings?

后端 未结 30 3260
予麋鹿
予麋鹿 2020-11-22 03:17

How can I generate a random 8 character alphanumeric string in C#?

30条回答
  •  星月不相逢
    2020-11-22 03:57

    Here is a mechanism to generate a random alpha-numeric string (I use this to generate passwords and test data) without defining the alphabet and numbers,

    CleanupBase64 will remove necessary parts in the string and keep adding random alpha-numeric letters recursively.

            public static string GenerateRandomString(int length)
            {
                var numArray = new byte[length];
                new RNGCryptoServiceProvider().GetBytes(numArray);
                return CleanUpBase64String(Convert.ToBase64String(numArray), length);
            }
    
            private static string CleanUpBase64String(string input, int maxLength)
            {
                input = input.Replace("-", "");
                input = input.Replace("=", "");
                input = input.Replace("/", "");
                input = input.Replace("+", "");
                input = input.Replace(" ", "");
                while (input.Length < maxLength)
                    input = input + GenerateRandomString(maxLength);
                return input.Length <= maxLength ?
                    input.ToUpper() : //In my case I want capital letters
                    input.ToUpper().Substring(0, maxLength);
            }
    

提交回复
热议问题