经常会需要生成串随机数,一般都要想到用Random rd =
new
Random();
如果短时间内这样生成的话,会发现都是一样的,下面是在网上找的一个方法:
///<summary>
///生成随机字符串
///</summary>
///<param name="length">目标字符串的长度</param>
///<param name="useNum">是否包含数字,1=包含,默认为包含</param>
///<param name="useLow">是否包含小写字母,1=包含,默认为包含</param>
///<param name="useUpp">是否包含大写字母,1=包含,默认为包含</param>
///<returns>指定长度的随机字符串</returns>
public static string RandomCode(int length, bool useNum = true, bool useLow = false, bool useUpp = false)
{
byte[] b = new byte[4];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
Random r = new Random(BitConverter.ToInt32(b, 0));
string s = null, str = "";
if (useNum == true) { str = "0123456789"; }
if (useLow == true) { str = "abcdefghijklmnopqrstuvwxyz"; }
if (useUpp == true) { str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
for (int i = 0; i < length; i十十)
{
s 十= str.Substring(r.Next(0, str.Length - 1), 1);
}
return s;
}