标签:
using System;
using System.Configuration;
using System.Text;
using System.Data;
namespace ZC.Utils
{
/// <summary>
/// Assistant 的摘要说明。
/// </summary>
public sealed class RandomHelper
{
#region
/// <summary>
/// 从字符串里随机得到,规定个数的字符串.
/// </summary>
/// <param name="allChar"></param>
/// <param name="CodeCount"></param>
/// <returns></returns>
public static string GetRandomCode(string allChar, int CodeCount)
{
//string allChar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] allCharArray = allChar.Split(‘,‘);
string RandomCode = "";
int temp = -1;
Random rand = new Random();
for (int i=0;i<CodeCount;i++)
{
if (temp != -1)
{
rand = new Random(temp*i*((int) DateTime.Now.Ticks));
}
int t = rand.Next(allCharArray.Length-1);
while (temp == t)
{
t = rand.Next(allCharArray.Length-1);
}
temp = t;
RandomCode += allCharArray[t];
}
return RandomCode;
}
/// <summary>
/// 从字符串里随机得到,规定个数的字符串.
/// </summary>
/// <param name="allChar"></param>
/// <param name="CodeCount"></param>
/// <returns></returns>
public static string GetRandomCode(int CodeCount)
{
string allChar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] allCharArray = allChar.Split(‘,‘);
string RandomCode = "";
int temp = -1;
Random rand = new Random(GetRandomSeed());
for (int i = 0; i < CodeCount; i++)
{
if (temp != -1)
{
//rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
rand = new Random(GetRandomSeed());
}
int t = rand.Next(allCharArray.Length - 1);
while (temp == t)
{
t = rand.Next(allCharArray.Length - 1);
}
temp = t;
RandomCode += allCharArray[t];
}
return RandomCode;
}
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);
}
#endregion
}
}
标签:
原文地址:http://www.cnblogs.com/huangdegen/p/4656719.html