且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中生成随机字符串?

更新时间:2023-10-03 08:35:46

如果您是指GUID,请使用System.GUID.NewGuid().

如果要生成的字符串/值不是GUID,则需要编写自己的逻辑(使用Random() 类).
If you mean a GUID, then use System.GUID.NewGuid().

If the string/value you want to generate is not a GUID, you will need to write your own logic (using the Random() class).


int patternsNum = 3;// the number of string serial want to create example 5: 44850-rt64x-xFtmt-tyuxu-cbhyt6
           int patternLength = 3; // the lenght of each pattern example 4: xtry
           string[] buff = new string[3];

           string patt = "";
           int xx = 64;
           for (int i = 0; i < patternsNum; i++)
           {
               patt = "";
               for (int j = 0; j < patternLength; j++)
               {
                   Random pat = new Random(64);
                   int inte = xx + pat.Next(32) ;
                   xx = inte+Convert.ToInt16(DateTime.Now.Second);
                   char ch = Convert.ToChar(inte);
                   patt += ch.ToString();
               }
               buff[i] = patt;
           }

           // out:
           foreach (string x in buff)
           {
               MessageBox.Show(x);
           }