/// <summary>
/// 生成随机数
/// </summary>
/// <param name="codeLen">数据的长度</param>
/// <returns></returns>
public string CreateRandomCode(int codeLen)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";// 若想生成验证码则通常会去掉类似的字符,如:O与0、I与1
string[] allCharAry = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeLen; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));// 保证随机性跟严谨
}
int t = rand.Next(35);// allChar数组索引最大值
if (temp == t)
{
return CreateRandomCode(codeLen);//防止随机字符串中两个相邻的字符相等
}
temp = t;
randomCode += allCharAry[t];
}
return randomCode;
}
2020-07-31
C#获取相邻字符不相等的随机字符串(0~9,A~Z,或自定义)
生成随机字符串
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment