1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/// <summary>
/// 获取随机字符串
/// </summary>
/// <param name="Length">长度</param>
/// <returns></returns>
public static string GenerateRandom(int Length)
{
long tick = DateTime.Now.Ticks;
var seed = (int)(tick & 0xffffffffL) | (int)(tick >> 32);
//var seed = GetRandomSeed();
Random rd = new Random(seed);
return GenerateRandom(rd, Length);
}
/// <summary>
/// 获取随机字符串
/// </summary>
/// <param name="Length">长度</param>
/// <returns></returns>
public static string GenerateRandom(Random rd, int Length)
{
string strSep = ",";
char[] chrSep = strSep.ToCharArray();
string strChar = "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"
+ ",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";
string[] aryChar = strChar.Split(chrSep, strChar.Length);
StringBuilder newRandom = new StringBuilder(52);
for (int i = 0; i < Length; i++)
{
newRandom.Append(aryChar[rd.Next(aryChar.Length)]);
}
return newRandom.ToString();
}
/// <summary>
/// 产生随机种子
/// </summary>
/// <returns></returns>
static int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
本文会经常更新,请阅读原文: https://dashenxian.github.io/post/RadomString ,以避免陈旧错误知识的误导,同时有更好的阅读体验。
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 小神仙 (包含链接: https://dashenxian.github.io ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (125880321@qq.com) 。