.net工具类——获取编码(生成随机数)
.net工具类——获取编码(生成随机数)
- GetNumber:获取编码。年月日+八位随机数
- GetNumber2:获取编码。随机数
- GenerateCode:获取编码。包含大写英文和数字、去掉字母I和O
- GetCodePerfix:获取编码的前缀,年月(格式如:AK,表示2018年11月)
/// <summary> /// 获取编码。年月日+八位随机数 /// </summary> /// <returns></returns> public static string GetNumber() { byte[] buffer = Guid.NewGuid().ToByteArray(); var ram = BitConverter.ToInt64(buffer, 0); var str = string.Format("{0}{1}", Utils.GetRamCode2(), ram.ToString().Substring(0, 8)); return str; //var str = string.Format("{0}{1}", Utils.GetRamCode2(), Utils.Number(6, true)); //return str; } /// <summary> /// 获取编码。随机数 /// </summary> /// <returns></returns> public static string GetNumber2(int Length) { byte[] buffer = Guid.NewGuid().ToByteArray(); var ram = BitConverter.ToInt64(buffer, 0); var str = string.Format("{0}", ram.ToString().Substring(0, Length)); return str; } /// <summary> /// 获取编码。年月日+八位随机数 /// </summary> /// <returns></returns> public static string GetNumber(List<string> listNumber) { string Number = GetNumber(); int i = 0; while (true) { ++i; if (listNumber.Contains(Number)) { Number = GetNumber(); } else { break; } if (i > 10) { LogHelper.WriteLog("GetNumber已经执行了{i}次!"); } } return Number; } /// <summary> /// 获取编码。随机数 /// </summary> /// <returns></returns> public static string GetNumber2(int Length, List<string> listNumber) { string Number = GetNumber2(Length); int i = 0; while (true) { ++i; if (listNumber.Contains(Number)) { Number = GetNumber2(Length); } else { break; } if (i > 10) { LogHelper.WriteLog("GetNumber已经执行了{i}次!"); } } return Number; } /// <summary> /// 包含大写英文和数字、去掉字母I和O /// </summary> private static char[] constant = { '0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z' }; /// <summary> /// 获取编码。包含大写英文和数字、去掉字母I和O /// </summary> /// <returns></returns> public static string GenerateCode(int Length) { Thread.Sleep(10); StringBuilder newRandom = new StringBuilder(34); Random rd = new Random(); for (int i = 0; i < Length; i++) { newRandom.Append(constant[rd.Next(34)]); } return newRandom.ToString(); } /// <summary> /// 获取编码。包含大写英文和数字、去掉字母I和O /// </summary> /// <returns></returns> public static string GenerateCode(int Length, List<string> listNumber) { string Number = GenerateCode(Length); int i = 0; while (true) { ++i; if (listNumber.Contains(Number)) { Number = GenerateCode(Length); } else { break; } if (i > 10) { LogHelper.WriteLog($"GenerateCode已经执行了{i}次!"); } } return Number; } /// <summary> /// 获取编码的前缀,年月(格式如:AK,表示2018年11月) /// </summary> /// <returns></returns> public static string GetCodePerfix() { var dtNow = DateTime.Now; int thisYear = dtNow.Year; int thisMonth = dtNow.Month; int year = 'A' + (thisYear - 2018);//从2018年开始 int month = 'A' + (thisMonth - 1);//从一月开始 return (char)year + "" + (char)+month; }