CommonFun.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. using System.Reflection.Metadata;
  2. namespace OASystem.Infrastructure.Tools;
  3. /// <summary>
  4. /// 工具类
  5. /// </summary>
  6. public static class CommonFun
  7. {
  8. public static string GUID => Guid.NewGuid().ToString("N");
  9. public static bool IsNull(this string s)
  10. {
  11. return string.IsNullOrWhiteSpace(s);
  12. }
  13. public static bool NotNull(this string s)
  14. {
  15. return !string.IsNullOrWhiteSpace(s);
  16. }
  17. public static int GetRandom(int minNum, int maxNum)
  18. {
  19. var seed = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
  20. return new Random(seed).Next(minNum, maxNum);
  21. }
  22. public static string GetSerialNumber(string prefix = "")
  23. {
  24. return prefix + DateTime.Now.ToString("yyyyMMddHHmmssfff") + GetRandom(1000, 9999).ToString();
  25. }
  26. public static string ToJson(this object obj)
  27. {
  28. return JsonSerializer.Serialize(obj);
  29. }
  30. public static T ToObject<T>(this string json)
  31. {
  32. return JsonSerializer.Deserialize<T>(json);
  33. }
  34. public static object GetDefaultVal(string typename)
  35. {
  36. return typename switch
  37. {
  38. "Boolean" => false,
  39. "DateTime" => default(DateTime),
  40. "Date" => default(DateTime),
  41. "Double" => 0.0,
  42. "Single" => 0f,
  43. "Int32" => 0,
  44. "String" => string.Empty,
  45. "Decimal" => 0m,
  46. _ => null,
  47. };
  48. }
  49. public static void CoverNull<T>(T model) where T : class
  50. {
  51. if (model == null)
  52. {
  53. return;
  54. }
  55. var typeFromHandle = typeof(T);
  56. var properties = typeFromHandle.GetProperties();
  57. var array = properties;
  58. for (var i = 0; i < array.Length; i++)
  59. {
  60. var propertyInfo = array[i];
  61. if (propertyInfo.GetValue(model, null) == null)
  62. {
  63. propertyInfo.SetValue(model, GetDefaultVal(propertyInfo.PropertyType.Name), null);
  64. }
  65. }
  66. }
  67. public static void CoverNull<T>(List<T> models) where T : class
  68. {
  69. if (models.Count == 0)
  70. {
  71. return;
  72. }
  73. foreach (var model in models)
  74. {
  75. CoverNull(model);
  76. }
  77. }
  78. public static bool ToBool(this object thisValue, bool errorvalue = false)
  79. {
  80. if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out bool reval))
  81. {
  82. return reval;
  83. }
  84. return errorvalue;
  85. }
  86. #region 文件操作
  87. public static FileInfo[] GetFiles(string directoryPath)
  88. {
  89. if (!IsExistDirectory(directoryPath))
  90. {
  91. throw new DirectoryNotFoundException();
  92. }
  93. var root = new DirectoryInfo(directoryPath);
  94. return root.GetFiles();
  95. }
  96. public static bool IsExistDirectory(string directoryPath)
  97. {
  98. return Directory.Exists(directoryPath);
  99. }
  100. public static string ReadFile(string Path)
  101. {
  102. string s;
  103. if (!File.Exists(Path))
  104. s = "不存在相应的目录";
  105. else
  106. {
  107. var f2 = new StreamReader(Path, Encoding.Default);
  108. s = f2.ReadToEnd();
  109. f2.Close();
  110. f2.Dispose();
  111. }
  112. return s;
  113. }
  114. public static void FileMove(string OrignFile, string NewFile)
  115. {
  116. File.Move(OrignFile, NewFile);
  117. }
  118. public static void CreateDir(string dir)
  119. {
  120. if (dir.Length == 0) return;
  121. if (!Directory.Exists(dir))
  122. Directory.CreateDirectory(dir);
  123. }
  124. #endregion
  125. #region IP
  126. /// <summary>
  127. /// 是否为ip
  128. /// </summary>
  129. /// <param name="ip"></param>
  130. /// <returns></returns>
  131. public static bool IsIP(string ip)
  132. {
  133. return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
  134. }
  135. public static string GetIP(HttpRequest request)
  136. {
  137. if (request == null)
  138. {
  139. return "";
  140. }
  141. var ip = request.Headers["X-Real-IP"].FirstOrDefault();
  142. if (ip.IsNull())
  143. {
  144. ip = request.Headers["X-Forwarded-For"].FirstOrDefault();
  145. }
  146. if (ip.IsNull())
  147. {
  148. ip = request.HttpContext?.Connection?.RemoteIpAddress?.ToString();
  149. }
  150. if (ip.IsNull() || !IsIP(ip))
  151. {
  152. ip = "127.0.0.1";
  153. }
  154. return ip;
  155. }
  156. #endregion
  157. #region 随机数
  158. /// <summary>
  159. /// 根据自定义随机包含的字符获取指定长度的随机字符
  160. /// </summary>
  161. /// <param name="length">随机字符长度</param>
  162. /// <returns>随机字符</returns>
  163. public static string GetRandomStr(int length)
  164. {
  165. string a = "ABCDEFGHJKLMNPQRSTUVWXYZ012356789";
  166. StringBuilder sb = new StringBuilder();
  167. for (int i = 0; i < length; i++)
  168. {
  169. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  170. }
  171. return sb.ToString();
  172. }
  173. /// <summary>
  174. /// 根据自定义随机包含的字符获取指定长度的随机字符
  175. /// </summary>
  176. /// <param name="length">随机字符长度</param>
  177. /// <returns>随机字符</returns>
  178. public static string GetRandomAllStr(int length)
  179. {
  180. string a = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz012356789";
  181. StringBuilder sb = new StringBuilder();
  182. for (int i = 0; i < length; i++)
  183. {
  184. sb.Append(a[new Random(Guid.NewGuid().GetHashCode()).Next(0, a.Length - 1)]);
  185. }
  186. return sb.ToString();
  187. }
  188. #endregion
  189. #region decimal 截取
  190. /// <summary>
  191. ///
  192. /// </summary>
  193. /// <param name="d"></param>
  194. /// <param name="n"></param>
  195. /// <returns></returns>
  196. public static decimal CutDecimalWithN(decimal d, int n)
  197. {
  198. string strDecimal = d.ToString();
  199. int index = strDecimal.IndexOf(".");
  200. if (index == -1 || strDecimal.Length < index + n + 1)
  201. {
  202. strDecimal = string.Format("{0:F" + n + "}", d);
  203. }
  204. else
  205. {
  206. int length = index;
  207. if (n != 0)
  208. {
  209. length = index + n + 1;
  210. }
  211. strDecimal = strDecimal.Substring(0, length);
  212. }
  213. return Decimal.Parse(strDecimal);
  214. }
  215. public static decimal CutDecimalWithN(decimal? d, int n)
  216. {
  217. if (d == null)
  218. {
  219. return Decimal.MinValue;
  220. }
  221. return CutDecimalWithN(Convert.ToDecimal(d), n);
  222. }
  223. #endregion
  224. }