StringUtils.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Converters;
  8. namespace GxPress.Common.Tools
  9. {
  10. public static class StringUtils
  11. {
  12. private static string AddressUrl = ConfigHelper.GetValue("ServiceAddress:AddressUrl");
  13. public static bool EqualsIgnoreCase(string a, string b)
  14. {
  15. if (a == b) return true;
  16. if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false;
  17. return a.Equals(b, StringComparison.OrdinalIgnoreCase);
  18. }
  19. public static DateTime SqlMinValue { get; } = new DateTime(1754, 1, 1, 0, 0, 0, 0);
  20. public static DateTime ToDateTime(string dateTimeStr)
  21. {
  22. var datetime = SqlMinValue;
  23. if (!string.IsNullOrEmpty(dateTimeStr))
  24. {
  25. if (!DateTime.TryParse(dateTimeStr.Trim(), out datetime))
  26. {
  27. datetime = SqlMinValue;
  28. }
  29. }
  30. if (datetime < SqlMinValue)
  31. {
  32. datetime = SqlMinValue;
  33. }
  34. return datetime;
  35. }
  36. /// <summary>
  37. /// 移除Emoji
  38. /// </summary>
  39. /// <param name="str"></param>
  40. /// <returns></returns>
  41. public static string RemoveEmoji(string str)
  42. {
  43. if (string.IsNullOrWhiteSpace(str))
  44. return string.Empty;
  45. foreach (var a in str)
  46. {
  47. byte[] bts = Encoding.UTF32.GetBytes(a.ToString());
  48. if (bts[0].ToString() == "253" && bts[1].ToString() == "255")
  49. {
  50. str = str.Replace(a.ToString(), "");
  51. }
  52. }
  53. return str;
  54. }
  55. public static T ToEnum<T>(this string value, T defaultValue) where T : struct
  56. {
  57. if (string.IsNullOrEmpty(value))
  58. {
  59. return defaultValue;
  60. }
  61. return Enum.TryParse<T>(value, true, out var result) ? result : defaultValue;
  62. }
  63. public static int ToInt(string value)
  64. {
  65. return int.TryParse(value, out var result) ? result : 0;
  66. }
  67. public static IEnumerable<string> StringCollectionToStringList(string collection, char split = ',')
  68. {
  69. var list = new List<string>();
  70. if (!string.IsNullOrEmpty(collection))
  71. {
  72. var array = collection.Split(split);
  73. foreach (var s in array)
  74. {
  75. list.Add(s);
  76. }
  77. }
  78. return list;
  79. }
  80. public static IEnumerable<int> StringCollectionToIntList(string collection, char split = ',')
  81. {
  82. var list = new List<int>();
  83. if (!string.IsNullOrEmpty(collection))
  84. {
  85. var array = collection.Split(split);
  86. foreach (var s in array)
  87. {
  88. list.Add(Convert.ToInt32(s));
  89. }
  90. }
  91. return list;
  92. }
  93. public static string ObjectCollectionToString(IEnumerable<string> collection)
  94. {
  95. var builder = new StringBuilder();
  96. if (collection != null)
  97. {
  98. foreach (var obj in collection)
  99. {
  100. builder.Append(obj.Trim()).Append(",");
  101. }
  102. if (builder.Length != 0) builder.Remove(builder.Length - 1, 1);
  103. }
  104. return builder.ToString();
  105. }
  106. public static string ObjectCollectionToString(IEnumerable<string> collection, string charValue)
  107. {
  108. if (collection.Count() == 0)
  109. return string.Empty;
  110. var builder = new StringBuilder();
  111. if (collection != null)
  112. {
  113. foreach (var obj in collection)
  114. {
  115. if (!string.IsNullOrWhiteSpace(obj))
  116. builder.Append(obj.Trim()).Append(charValue);
  117. }
  118. if (builder.Length != 0) builder.Remove(builder.Length - 1, 1);
  119. }
  120. return builder.ToString();
  121. }
  122. public static string ObjectCollectionToString(IEnumerable<int> collection)
  123. {
  124. var builder = new StringBuilder();
  125. if (collection != null)
  126. {
  127. foreach (var obj in collection)
  128. {
  129. builder.Append(obj).Append(",");
  130. }
  131. if (builder.Length != 0) builder.Remove(builder.Length - 1, 1);
  132. }
  133. return builder.ToString();
  134. }
  135. public static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings
  136. {
  137. //ContractResolver = new CamelCasePropertyNamesContractResolver(),
  138. Converters = new List<JsonConverter>
  139. {
  140. new IsoDateTimeConverter {DateTimeFormat = "yyyy-MM-dd HH:mm:ss"}
  141. }
  142. };
  143. public static string JsonSerialize(object obj)
  144. {
  145. try
  146. {
  147. //var settings = new JsonSerializerSettings
  148. //{
  149. // ContractResolver = new CamelCasePropertyNamesContractResolver()
  150. //};
  151. //var timeFormat = new IsoDateTimeConverter {DateTimeFormat = "yyyy-MM-dd HH:mm:ss"};
  152. //settings.Converters.Add(timeFormat);
  153. return JsonConvert.SerializeObject(obj, JsonSettings);
  154. }
  155. catch
  156. {
  157. return string.Empty;
  158. }
  159. }
  160. public static T JsonDeserialize<T>(string json, T defaultValue = default(T))
  161. {
  162. try
  163. {
  164. //var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
  165. //var timeFormat = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
  166. //settings.Converters.Add(timeFormat);
  167. return JsonConvert.DeserializeObject<T>(json, JsonSettings);
  168. }
  169. catch
  170. {
  171. return defaultValue;
  172. }
  173. }
  174. public static string GetWebRootPath(string webRootPath)
  175. {
  176. if (string.IsNullOrWhiteSpace(webRootPath))
  177. {
  178. webRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
  179. }
  180. return webRootPath;
  181. }
  182. public static bool IsGuid(string val)
  183. {
  184. return !string.IsNullOrWhiteSpace(val) && Guid.TryParse(val, out _);
  185. }
  186. public static string ShortGuid(string guid)
  187. {
  188. if (!IsGuid(guid))
  189. {
  190. guid = Guid.NewGuid().ToString();
  191. }
  192. long i = 1;
  193. foreach (var b in Guid.Parse(guid).ToByteArray())
  194. {
  195. i *= b + 1;
  196. }
  197. return $"{i - DateTime.Now.Ticks:x}";
  198. }
  199. public static bool IsDomain(string url)
  200. {
  201. if (string.IsNullOrEmpty(url)) return false;
  202. return Uri.IsWellFormedUriString(url, UriKind.Absolute);
  203. }
  204. public static string RemoveDomain(string url)
  205. {
  206. if (string.IsNullOrEmpty(url)) return string.Empty;
  207. return IsDomain(url) ? new Uri(url).PathAndQuery : url;
  208. }
  209. public static string AddDomain(string url)
  210. {
  211. if (string.IsNullOrEmpty(url)) return string.Empty;
  212. return IsDomain(url) ? url : $"{AddressUrl}" + url;
  213. }
  214. public static string AddPathDomain(string url)
  215. {
  216. if (string.IsNullOrEmpty(url)) return string.Empty;
  217. var startPath = Directory.GetCurrentDirectory() + "\\wwwroot";
  218. var path = Path.Combine(startPath + url).Replace("/", "\\");
  219. return path;
  220. }
  221. public static string AddDomainMin(string url, int width = 50)
  222. {
  223. if (string.IsNullOrEmpty(url)) return $"{AddressUrl}/cache/20191123/ff2a342a68fb4c3dbdcdac877b8b3727.png";
  224. var urlSpl = url.Split('.');
  225. var imgType = urlSpl[urlSpl.Length - 1];
  226. var imageName = $"_{width}_{width}.{imgType}";
  227. url = url.Replace($".{imgType}", imageName);
  228. url = IsDomain(url) ? url : $"{AddressUrl}" + url;
  229. return url.Replace("///", "/");
  230. }
  231. public static string GetPreviewDocUrl(string url)
  232. {
  233. return $"http://ow365.cn/?i=20124&furl={AddDomain(url)}";
  234. }
  235. public static int GetDate(DateTime? dateTime)
  236. {
  237. return dateTime.HasValue ? ToInt(dateTime.Value.ToString("yyyyMMdd")) : ToInt(DateTime.Now.ToString("yyyyMMdd"));
  238. }
  239. public static string GetFlowNo(DateTime? createdDate, int flowId)
  240. {
  241. return (createdDate ?? DateTime.Now).ToString("yyyyMMddHHmmss") + flowId.ToString().PadLeft(4, '0');
  242. }
  243. /// <summary>
  244. /// 计算文件大小函数(保留两位小数),Size为字节大小
  245. /// </summary>
  246. /// <param name="Size">初始文件大小</param>
  247. /// <returns></returns>
  248. public static string CountSize(long Size)
  249. {
  250. string m_strSize = "";
  251. long FactSize = 0;
  252. FactSize = Size;
  253. if (FactSize < 1024.00)
  254. m_strSize = FactSize.ToString("F2") + " Byte";
  255. else if (FactSize >= 1024.00 && FactSize < 1048576)
  256. m_strSize = (FactSize / 1024.00).ToString("F2") + " K";
  257. else if (FactSize >= 1048576 && FactSize < 1073741824)
  258. m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";
  259. else if (FactSize >= 1073741824)
  260. m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";
  261. return m_strSize;
  262. }
  263. }
  264. }