C# 生成真随机字符串
随机字符串这么简单的一个功能,网上搜到的结果却很多要求必须安装 mscorlib.dll, netstandard.dll組件,实在不方便。还是自己写吧不需要引入不需要安装的
/// < summary>
/// 生成随机字符串
/// < /summary>
/// 长度
public string GenerateRandomString(int length)
{
string result = "";
Random ran = new Random();
string dictionary = "0123456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
int len = dictionary.Length;
char[] arrList = dictionary.ToCharArray();
for (int i = 0; i < length; i++)
{
int RandKey = ran.Next(0, len - 1);
result += arrList[RandKey];
}
return result;
}
测试生成1000个
string[] pwds = new string[1000];
for (int i = 0; i < 1000; i++)
{
pwds[i] = GenerateRandomString(9);
}
Console.WriteLine(pwds);
最终输出,没有出现重复数据:
"HiYRrUQbN",
"2Th1y71oJ",
"0bGQOLRhC",
"Rv5AcR0N8",
"a9dvJRGvy",
"w7qNTFrkJ",
"LEThaAkKN",
"8xotDG0ch",
"UnHFjsXfN",
"V40O83BWF",
"9wkQCJ8XU",
"t8yQQQrBC",
"jOoa8P2Yh",
"DNjVg7w0G",
...
C# 也提供一个方法直接生成随机密码
public static string GeneratePassword(int length, int numberOfNonAlphanumericCharacters);
不过您需要安装库文件
Namespace: System.Web.Security
Assembly:System.Web.dll