How can I generate random alphanumeric strings?

后端 未结 30 3269
予麋鹿
予麋鹿 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 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.

提交回复
热议问题