How can I generate random alphanumeric strings?

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

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

相关标签:
30条回答
  • 2020-11-22 03:56
    public static class StringHelper
    {
        private static readonly Random random = new Random();
    
        private const int randomSymbolsDefaultCount = 8;
        private const string availableChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
        private static int randomSymbolsIndex = 0;
    
        public static string GetRandomSymbols()
        {
            return GetRandomSymbols(randomSymbolsDefaultCount);
        }
    
        public static string GetRandomSymbols(int count)
        {
            var index = randomSymbolsIndex;
            var result = new string(
                Enumerable.Repeat(availableChars, count)
                          .Select(s => {
                              index += random.Next(s.Length);
                              if (index >= s.Length)
                                  index -= s.Length;
                              return s[index];
                          })
                          .ToArray());
            randomSymbolsIndex = index;
            return result;
        }
    }
    
    0 讨论(0)
  • 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);
            }
    
    0 讨论(0)
  • 2020-11-22 03:58

    A solution without using Random :

    var chars = Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 8);
    
    var randomStr = new string(chars.SelectMany(str => str)
                                    .OrderBy(c => Guid.NewGuid())
                                    .Take(8).ToArray());
    
    0 讨论(0)
  • 2020-11-22 03:58

    If your values are not completely random, but in fact may depend on something - you may compute an md5 or sha1 hash of that 'somwthing' and then truncate it to whatever length you want.

    Also you may generate and truncate a guid.

    0 讨论(0)
  • 2020-11-22 03:58

    not 100% sure, as I didn't test EVERY option here, but of the ones I did test, this one is the fastest. timed it with stopwatch and it showed 9-10 ticks so if speed is more important than security, try this:

     private static Random random = new Random(); 
     public static string Random(int length)
         {   
              var stringChars = new char[length];
    
              for (int i = 0; i < length; i++)
                  {
                      stringChars[i] = (char)random.Next(0x30, 0x7a);                  
                      return new string(stringChars);
                  }
         }
    
    0 讨论(0)
  • 2020-11-22 04:00

    A slightly cleaner version of DTB's solution.

        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var random = new Random();
        var list = Enumerable.Repeat(0, 8).Select(x=>chars[random.Next(chars.Length)]);
        return string.Join("", list);
    

    Your style preferences may vary.

    0 讨论(0)
提交回复
热议问题