How can I generate random alphanumeric strings?

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

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

30条回答
  •  无人及你
    2020-11-22 03:46

    Try to combine two parts: unique (sequence, counter or date ) and random

    public class RandomStringGenerator
    {
        public static string Gen()
        {
            return ConvertToBase(DateTime.UtcNow.ToFileTimeUtc()) + GenRandomStrings(5); //keep length fixed at least of one part
        }
    
        private static string GenRandomStrings(int strLen)
        {
            var result = string.Empty;
    
            using (var gen = new RNGCryptoServiceProvider())
            {
                var data = new byte[1];
    
                while (result.Length < strLen)
                {
                    gen.GetNonZeroBytes(data);
                    int code = data[0];
                    if (code > 48 && code < 57 || // 0-9
                        code > 65 && code < 90 || // A-Z
                        code > 97 && code < 122   // a-z
                    )
                    {
                        result += Convert.ToChar(code);
                    }
                }
    
                return result;
            }
        }
    
        private static string ConvertToBase(long num, int nbase = 36)
        {
            const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //if you wish to make the algorithm more secure - change order of letter here
    
            // check if we can convert to another base
            if (nbase < 2 || nbase > chars.Length)
                return null;
    
            int r;
            var newNumber = string.Empty;
    
            // in r we have the offset of the char that was converted to the new base
            while (num >= nbase)
            {
                r = (int)(num % nbase);
                newNumber = chars[r] + newNumber;
                num = num / nbase;
            }
            // the last number to convert
            newNumber = chars[(int)num] + newNumber;
    
            return newNumber;
        }
    }
    

    Tests:

        [Test]
        public void Generator_Should_BeUnigue1()
        {
            //Given
            var loop = Enumerable.Range(0, 1000);
            //When
            var str = loop.Select(x=> RandomStringGenerator.Gen());
            //Then
            var distinct = str.Distinct();
            Assert.AreEqual(loop.Count(),distinct.Count()); // Or Assert.IsTrue(distinct.Count() < 0.95 * loop.Count())
        }
    

提交回复
热议问题