1. 程式人生 > 實用技巧 >.net工具類——隨機生成

.net工具類——隨機生成

.net工具類——隨機生成

  1. GetRamCode:生成日期隨機碼(年月日時分秒毫秒)
  2. Number:生成隨機數字
  3. GetCheckCode:生成隨機字母字串(數字字母混和)
  4. GetOrderNumber:根據日期和隨機碼生成訂單號
  5. Next

     
        #region 生成日期隨機碼

        /// <summary>
        /// 生成日期隨機碼(年月日時分秒毫秒)
        /// </summary>
        /// <returns></returns>
        public static
string GetRamCode() { #region return DateTime.Now.ToString("yyyyMMddHHmmssffff"); #endregion 生成日期隨機碼 } /// <summary> /// 生成日期隨機碼(年月日) /// </summary> /// <returns></returns> public static string GetRamCode2() {
#region return DateTime.Now.ToString("yyyyMMdd"); #endregion 生成日期隨機碼 } #endregion #region 生成隨機字母或數字 /// <summary> /// 生成隨機數字 /// </summary> /// <param name="length">生成長度</param> /// <returns></returns>
public static string Number(int Length) { return Number(Length, false); } /// <summary> /// 生成隨機數字 /// </summary> /// <param name="Length">生成長度</param> /// <param name="Sleep">是否要在生成前將當前執行緒阻止以避免重複</param> /// <returns></returns> public static string Number(int Length, bool Sleep) { if (Sleep) System.Threading.Thread.Sleep(3); string result = ""; System.Random random = new Random(); for (int i = 0; i < Length; i++) { result += random.Next(10).ToString(); } return result; } /// <summary> /// 生成隨機字母字串(數字字母混和) /// </summary> /// <param name="codeCount">待生成的位數</param> public static string GetCheckCode(int codeCount) { string str = string.Empty; int rep = 0; long num2 = DateTime.Now.Ticks + rep; rep++; Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep))); for (int i = 0; i < codeCount; i++) { char ch; int num = random.Next(); if ((num % 2) == 0) { ch = (char)(0x30 + ((ushort)(num % 10))); } else { ch = (char)(0x41 + ((ushort)(num % 0x1a))); } str = str + ch.ToString(); } return str; } /// <summary> /// 根據日期和隨機碼生成訂單號 /// </summary> /// <returns></returns> public static string GetOrderNumber() { string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms return num + Number(2).ToString(); } private static int Next(int numSeeds, int length) { byte[] buffer = new byte[length]; System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider(); Gen.GetBytes(buffer); uint randomResult = 0x0;//這裡用uint作為生成的隨機數 for (int i = 0; i < length; i++) { randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8)); } return (int)(randomResult % numSeeds); } #endregion