CodeCreator.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Text;
  3. namespace WingDeviceService.Common
  4. {
  5. public class CodeCreator
  6. {
  7. private CodeCreator(){}
  8. /// <summary>
  9. /// 生成单个随机数字
  10. /// </summary>
  11. private static int CreateNum()
  12. {
  13. Random random = new Random(Guid.NewGuid().GetHashCode());
  14. int num = random.Next(10);
  15. return num;
  16. }
  17. /// <summary>
  18. /// 生成单个大写随机字母
  19. /// </summary>
  20. private static string CreateBigAbc()
  21. {
  22. //A-Z的 ASCII值为65-90
  23. Random random = new Random(Guid.NewGuid().GetHashCode());
  24. int num = random.Next(65, 91);
  25. string abc = Convert.ToChar(num).ToString();
  26. return abc;
  27. }
  28. /// <summary>
  29. /// 生成单个小写随机字母
  30. /// </summary>
  31. private static string CreateSmallAbc()
  32. {
  33. //a-z的 ASCII值为97-122
  34. Random random = new Random(Guid.NewGuid().GetHashCode());
  35. int num = random.Next(97, 123);
  36. string abc = Convert.ToChar(num).ToString();
  37. return abc;
  38. }
  39. /// <summary>
  40. /// 生成随机字符串
  41. /// </summary>
  42. /// <param name="length">字符串的长度</param>
  43. /// <returns></returns>
  44. public static string CreateRandomStr(int length)
  45. {
  46. // 创建一个StringBuilder对象存储密码
  47. StringBuilder sb = new StringBuilder();
  48. //使用for循环把单个字符填充进StringBuilder对象里面变成14位密码字符串
  49. for (int i = 0; i < length; i++)
  50. {
  51. Random random = new Random(Guid.NewGuid().GetHashCode());
  52. //随机选择里面其中的一种字符生成
  53. switch (random.Next(3))
  54. {
  55. case 0:
  56. //调用生成生成随机数字的方法
  57. sb.Append(CreateNum());
  58. break;
  59. case 1:
  60. //调用生成生成随机小写字母的方法
  61. sb.Append(CreateSmallAbc());
  62. break;
  63. case 2:
  64. //调用生成生成随机大写字母的方法
  65. sb.Append(CreateBigAbc());
  66. break;
  67. }
  68. }
  69. return sb.ToString();
  70. }
  71. /// <summary>
  72. /// 创建编码
  73. /// </summary>
  74. /// <param name="prefix"></param>
  75. /// <returns></returns>
  76. public static string CreateCode(string prefix)
  77. {
  78. return WingServerCommon.Utilities.IdHelper.Generate<string>();
  79. }
  80. }
  81. }