How can I generate random alphanumeric strings?

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

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

30条回答
  •  太阳男子
    2020-11-22 04:09

    Horrible, I know, but I just couldn't help myself:

    
    namespace ConsoleApplication2
    {
        using System;
        using System.Text.RegularExpressions;
    
        class Program
        {
            static void Main(string[] args)
            {
                Random adomRng = new Random();
                string rndString = string.Empty;
                char c;
    
                for (int i = 0; i < 8; i++)
                {
                    while (!Regex.IsMatch((c=Convert.ToChar(adomRng.Next(48,128))).ToString(), "[A-Za-z0-9]"));
                    rndString += c;
                }
    
                Console.WriteLine(rndString + Environment.NewLine);
            }
        }
    }
    
    

提交回复
热议问题