How can I generate random alphanumeric strings?

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

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

相关标签:
30条回答
  • 2020-11-22 04:01

    The simplest:

    public static string GetRandomAlphaNumeric()
    {
        return Path.GetRandomFileName().Replace(".", "").Substring(0, 8);
    }
    

    You can get better performance if you hard code the char array and rely on System.Random:

    public static string GetRandomAlphaNumeric()
    {
        var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        return new string(chars.Select(c => chars[random.Next(chars.Length)]).Take(8).ToArray());
    }
    

    If ever you worry the English alphabets can change sometime around and you might lose business, then you can avoid hard coding, but should perform slightly worse (comparable to Path.GetRandomFileName approach)

    public static string GetRandomAlphaNumeric()
    {
        var chars = 'a'.To('z').Concat('0'.To('9')).ToList();
        return new string(chars.Select(c => chars[random.Next(chars.Length)]).Take(8).ToArray());
    }
    
    public static IEnumerable<char> To(this char start, char end)
    {
        if (end < start)
            throw new ArgumentOutOfRangeException("the end char should not be less than start char", innerException: null);
        return Enumerable.Range(start, end - start + 1).Select(i => (char)i);
    }
    

    The last two approaches looks better if you can make them an extension method on System.Random instance.

    0 讨论(0)
  • 2020-11-22 04:01

    My simple one line code works for me :)

    string  random = string.Join("", Guid.NewGuid().ToString("n").Take(8).Select(o => o));
    
    Response.Write(random.ToUpper());
    Response.Write(random.ToLower());
    

    To expand on this for any length string

        public static string RandomString(int length)
        {
            //length = length < 0 ? length * -1 : length;
            var str = "";
    
            do 
            {
                str += Guid.NewGuid().ToString().Replace("-", "");
            }
    
            while (length > str.Length);
    
            return str.Substring(0, length);
        }
    
    0 讨论(0)
  • 2020-11-22 04:04

    I heard LINQ is the new black, so here's my attempt using LINQ:

    private static Random random = new Random();
    public static string RandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }
    

    (Note: The use of the Random class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider class if you need a strong random number generator.)

    0 讨论(0)
  • 2020-11-22 04:04

    Another option could be to use Linq and aggregate random chars into a stringbuilder.

    var chars = "abcdefghijklmnopqrstuvwxyz123456789".ToArray();
    string pw = Enumerable.Range(0, passwordLength)
                          .Aggregate(
                              new StringBuilder(),
                              (sb, n) => sb.Append((chars[random.Next(chars.Length)])),
                              sb => sb.ToString());
    
    0 讨论(0)
  • 2020-11-22 04:04

    I don't know how cryptographically sound this is, but it's more readable and concise than the more intricate solutions by far (imo), and it should be more "random" than System.Random-based solutions.

    return alphabet
        .OrderBy(c => Guid.NewGuid())
        .Take(strLength)
        .Aggregate(
            new StringBuilder(),
            (builder, c) => builder.Append(c))
        .ToString();
    

    I can't decide if I think this version or the next one is "prettier", but they give the exact same results:

    return new string(alphabet
        .OrderBy(o => Guid.NewGuid())
        .Take(strLength)
        .ToArray());
    

    Granted, it isn't optimized for speed, so if it's mission critical to generate millions of random strings every second, try another one!

    NOTE: This solution doesn't allow for repetitions of symbols in the alphabet, and the alphabet MUST be of equal or greater size than the output string, making this approach less desirable in some circumstances, it all depends on your use-case.

    0 讨论(0)
  • 2020-11-22 04:05
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var stringChars = new char[8];
    var random = new Random();
    
    for (int i = 0; i < stringChars.Length; i++)
    {
        stringChars[i] = chars[random.Next(chars.Length)];
    }
    
    var finalString = new String(stringChars);
    

    Not as elegant as the Linq solution.

    (Note: The use of the Random class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider class if you need a strong random number generator.)

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