StringUtils.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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, int length)
  107. {
  108. var builder = new StringBuilder();
  109. if (collection != null)
  110. {
  111. int i = 0;
  112. foreach (var obj in collection)
  113. {
  114. builder.Append(obj.Trim()).Append(",");
  115. if (i >= length)
  116. break;
  117. i++;
  118. }
  119. if (builder.Length != 0) builder.Remove(builder.Length - 1, 1);
  120. }
  121. return builder.ToString();
  122. }
  123. public static string ObjectCollectionToString(IEnumerable<string> collection, string charValue)
  124. {
  125. if (collection.Count() == 0)
  126. return string.Empty;
  127. var builder = new StringBuilder();
  128. if (collection != null)
  129. {
  130. foreach (var obj in collection)
  131. {
  132. if (!string.IsNullOrWhiteSpace(obj))
  133. builder.Append(obj.Trim()).Append(charValue);
  134. }
  135. if (builder.Length != 0) builder.Remove(builder.Length - 1, 1);
  136. }
  137. return builder.ToString();
  138. }
  139. public static string ObjectCollectionToString(IEnumerable<int> collection)
  140. {
  141. var builder = new StringBuilder();
  142. if (collection != null)
  143. {
  144. foreach (var obj in collection)
  145. {
  146. builder.Append(obj).Append(",");
  147. }
  148. if (builder.Length != 0) builder.Remove(builder.Length - 1, 1);
  149. }
  150. return builder.ToString();
  151. }
  152. public static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings
  153. {
  154. //ContractResolver = new CamelCasePropertyNamesContractResolver(),
  155. Converters = new List<JsonConverter>
  156. {
  157. new IsoDateTimeConverter {DateTimeFormat = "yyyy-MM-dd HH:mm:ss"}
  158. }
  159. };
  160. public static string JsonSerialize(object obj)
  161. {
  162. try
  163. {
  164. //var settings = new JsonSerializerSettings
  165. //{
  166. // ContractResolver = new CamelCasePropertyNamesContractResolver()
  167. //};
  168. //var timeFormat = new IsoDateTimeConverter {DateTimeFormat = "yyyy-MM-dd HH:mm:ss"};
  169. //settings.Converters.Add(timeFormat);
  170. return JsonConvert.SerializeObject(obj, JsonSettings);
  171. }
  172. catch
  173. {
  174. return string.Empty;
  175. }
  176. }
  177. public static T JsonDeserialize<T>(string json, T defaultValue = default(T))
  178. {
  179. try
  180. {
  181. //var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
  182. //var timeFormat = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
  183. //settings.Converters.Add(timeFormat);
  184. return JsonConvert.DeserializeObject<T>(json, JsonSettings);
  185. }
  186. catch
  187. {
  188. return defaultValue;
  189. }
  190. }
  191. public static string GetWebRootPath(string webRootPath)
  192. {
  193. if (string.IsNullOrWhiteSpace(webRootPath))
  194. {
  195. webRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
  196. }
  197. return webRootPath;
  198. }
  199. public static bool IsGuid(string val)
  200. {
  201. return !string.IsNullOrWhiteSpace(val) && Guid.TryParse(val, out _);
  202. }
  203. public static string ShortGuid(string guid)
  204. {
  205. if (!IsGuid(guid))
  206. {
  207. guid = Guid.NewGuid().ToString();
  208. }
  209. long i = 1;
  210. foreach (var b in Guid.Parse(guid).ToByteArray())
  211. {
  212. i *= b + 1;
  213. }
  214. return $"{i - DateTime.Now.Ticks:x}";
  215. }
  216. public static bool IsDomain(string url)
  217. {
  218. if (string.IsNullOrEmpty(url)) return false;
  219. return Uri.IsWellFormedUriString(url, UriKind.Absolute);
  220. }
  221. public static string RemoveDomain(string url)
  222. {
  223. if (string.IsNullOrEmpty(url)) return string.Empty;
  224. return IsDomain(url) ? new Uri(url).PathAndQuery : url;
  225. }
  226. public static string AddDomain(string url)
  227. {
  228. if (string.IsNullOrEmpty(url)) return string.Empty;
  229. return IsDomain(url) ? url : $"{AddressUrl}" + url;
  230. }
  231. public static string AddDomainMin(string url, int width = 50)
  232. {
  233. if (string.IsNullOrEmpty(url)) return $"{AddressUrl}/cache/20191123/ff2a342a68fb4c3dbdcdac877b8b3727.png";
  234. var urlSpl = url.Split('.');
  235. var imgType = urlSpl[urlSpl.Length - 1];
  236. var imageName = $"_{width}_{width}.{imgType}";
  237. url = url.Replace($".{imgType}", imageName);
  238. url = IsDomain(url) ? url : $"{AddressUrl}" + url;
  239. return url.Replace("///", "/");
  240. }
  241. public static string GetPreviewDocUrl(string url)
  242. {
  243. return $"http://ow365.cn/?i=20124&furl={AddDomain(url)}";
  244. }
  245. public static int GetDate(DateTime? dateTime)
  246. {
  247. return dateTime.HasValue ? ToInt(dateTime.Value.ToString("yyyyMMdd")) : ToInt(DateTime.Now.ToString("yyyyMMdd"));
  248. }
  249. public static string GetFlowNo(DateTime? createdDate, int flowId)
  250. {
  251. return (createdDate ?? DateTime.Now).ToString("yyyyMMddHHmmss") + flowId.ToString().PadLeft(4, '0');
  252. }
  253. /// <summary>
  254. /// 计算文件大小函数(保留两位小数),Size为字节大小
  255. /// </summary>
  256. /// <param name="Size">初始文件大小</param>
  257. /// <returns></returns>
  258. public static string CountSize(long Size)
  259. {
  260. string m_strSize = "";
  261. long FactSize = 0;
  262. FactSize = Size;
  263. if (FactSize < 1024.00)
  264. m_strSize = FactSize.ToString("F2") + " Byte";
  265. else if (FactSize >= 1024.00 && FactSize < 1048576)
  266. m_strSize = (FactSize / 1024.00).ToString("F2") + " K";
  267. else if (FactSize >= 1048576 && FactSize < 1073741824)
  268. m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";
  269. else if (FactSize >= 1073741824)
  270. m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";
  271. return m_strSize;
  272. }
  273. }
  274. }