主要是想把日期和其它因素考慮進來。
使用RNGCryptoServiceProvider類創建唯一的最多8位數字符串。
private static string GetUniqueKey() { int maxSize = 8; int minSize = 5; char[] chars = new char[62]; string a; a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; chars = a.ToCharArray(); int size = maxSize; byte[] data = new byte[1]; RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(data); size = maxSize; data = new byte[size]; crypto.GetNonZeroBytes(data); StringBuilder result = new StringBuilder(size); foreach (byte b in data) { result.Append(chars[b % (chars.Length - 1)]); } return result.ToString(); }
然後,
for(int i = 0; i < 10; i++) { string str = string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), GetUniqueKey()); Console.WriteLine(str); } Console.ReadKey();