这是我用来生成ID的代码。 我也将结果从'='等特殊字符中删除,并将14作为参数传递给此方法。
对不起之前没有更具体,我想要的是生成一个不超过20个字符长的唯一ID,只包含数字和字母,没有特殊字符。此ID可以从任何地方的任何计算机生成。我不能使用GUID,因为它长度超过20个字符。此ID将用作报告编号。
static long counter; //store and load the counter from persistent storage every time the program loads or closes.
private static string CreateRandomString(int length)
{
length -= 12 ; //12 digits are the counter
if (length <= 0)
throw new ArgumentOutOfRangeException("length");
long count = System.Threading.Interlocked.Increment(ref counter);
Byte[] randomBytes = new Byte[length * 3 / 4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
byte[] buf = new byte[8];
buf[0] = (byte)count;
buf[1] = (byte)(count >> 8);
buf[2] = (byte)(count >> 16);
buf[3] = (byte)(count >> 24);
buf[4] = (byte)(count >> 32);
buf[5] = (byte)(count >> 40);
buf[6] = (byte)(count >> 48);
buf[7] = (byte)(count >> 56);
return Convert.ToBase64String(buf) + Convert.ToBase64String(randomBytes);
}