C creates unique order numbers using time and random strings

  • 2021-09-20 21:19:08
  • OfStack

Use RNGCryptoServiceProvider class to create only 1 of the maximum 8-digit string, and then splice in front of the year, month, day, hours and seconds generated string, the maximum guarantee that the generated string is only 1.

You can also modify according to their own needs, the date can be taken to milliseconds, so that the generated string is only 1.


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();
}

Then call the method, as shown below, and produce different results each time


for (int i = 0; i < 10; i++)
{
  string str = string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), GetUniqueKey());
  Console.WriteLine(str);
}
Console.ReadKey();

Related articles: