Functions.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq.Expressions;
  5. using System.Runtime.Serialization;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. namespace ReleaseHelper.Utils
  10. {
  11. public static class Functions
  12. {
  13. //static byte[] Encrypt(string input)
  14. //{
  15. // StringBuilder sb = new StringBuilder();
  16. // int i = 0;
  17. // int offset = Variables.Const.KEY[0];
  18. // foreach (char c in input)
  19. // {
  20. // var c2 = Convert.ToChar(c + Variables.Const.KEY[i++] + offset);
  21. // sb.Append(c2);
  22. // }
  23. // return Encoding.UTF8.GetBytes(sb.ToString());
  24. //}
  25. //static string Decrypt(byte[] input)
  26. //{
  27. // StringBuilder sb = new StringBuilder();
  28. // int i = 0;
  29. // int offset = Variables.Const.KEY[0];
  30. // string s = Encoding.UTF8.GetString(input);
  31. // foreach (char b in s)
  32. // {
  33. // sb.Append(Convert.ToChar(b - offset - Variables.Const.KEY[i++]));
  34. // }
  35. // return sb.ToString();
  36. //}
  37. //public static string LoadUserPW(string n, byte[] pwd)
  38. //{
  39. // return Decrypt(pwd).Substring($"{n}_".Length);
  40. //}
  41. //public static byte[] DumpUserPW(string n, string pwd)
  42. //{
  43. // return Encrypt($"{n}_{pwd}");
  44. //}
  45. /// <summary>
  46. /// 字符串生成MD5
  47. /// </summary>
  48. /// <param name="s"></param>
  49. /// <returns></returns>
  50. public static string GenMd5(string s)
  51. {
  52. //就是比string往后一直加要好的优化容器
  53. StringBuilder sb = new StringBuilder();
  54. using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
  55. {
  56. //将输入字符串转换为字节数组并计算哈希。
  57. byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(s));
  58. //X为 十六进制 X都是大写 x都为小写
  59. //2为 每次都是两位数
  60. //假设有两个数10和26,正常情况十六进制显示0xA、0x1A,这样看起来不整齐,为了好看,可以指定"X2",这样显示出来就是:0x0A、0x1A。
  61. //遍历哈希数据的每个字节
  62. //并将每个字符串格式化为十六进制字符串。
  63. int length = data.Length;
  64. for (int i = 0; i < length; i++)
  65. {
  66. sb.Append(data[i].ToString("X2"));
  67. }
  68. }
  69. return sb.ToString();
  70. }
  71. /// <summary>
  72. /// 获取文件的MD5码
  73. /// </summary>
  74. /// <param name="fileName">传入的文件名(含路径及后缀名)</param>
  75. /// <returns></returns>
  76. /// <exception cref="Exception"></exception>
  77. public static string GenMd5HashFromFile(string fileName)
  78. {
  79. try
  80. {
  81. StringBuilder sb = new StringBuilder();
  82. using (MD5 md5 = new MD5CryptoServiceProvider())
  83. using (FileStream file = new FileStream(fileName, FileMode.Open))
  84. {
  85. byte[] retVal = md5.ComputeHash(file);
  86. //file.Close();
  87. for (int i = 0; i < retVal.Length; i++)
  88. {
  89. sb.Append(retVal[i].ToString("X2"));
  90. }
  91. }
  92. return sb.ToString();
  93. }
  94. catch (Exception ex)
  95. {
  96. throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
  97. }
  98. }
  99. /// <summary>
  100. /// 生成UUID
  101. /// </summary>
  102. /// <returns></returns>
  103. public static string GenUUID()
  104. {
  105. return Guid.NewGuid().ToString("N");
  106. }
  107. /// <summary>
  108. /// 深复制对象
  109. /// </summary>
  110. /// <typeparam name="T"></typeparam>
  111. /// <param name="source"></param>
  112. /// <returns></returns>
  113. /// <exception cref="ArgumentException"></exception>
  114. public static T Clone<T>(T source)
  115. {
  116. if (!typeof(T).IsSerializable)
  117. {
  118. throw new ArgumentException("The type must be serializable.", "source");
  119. }
  120. // Don't serialize a null object, simply return the default for that object
  121. if (source == null)
  122. {
  123. return default;
  124. }
  125. IFormatter formatter = new BinaryFormatter();
  126. //Stream stream = new MemoryStream();
  127. using (Stream stream = new MemoryStream())
  128. {
  129. formatter.Serialize(stream, source);
  130. stream.Seek(0, SeekOrigin.Begin);
  131. return (T)formatter.Deserialize(stream);
  132. }
  133. }
  134. /// <summary>
  135. /// 生成任务id
  136. /// </summary>
  137. /// <param name="testId"></param>
  138. /// <returns></returns>
  139. public static string GenTaskId(int testId)
  140. {
  141. return GenTaskId(testId, Utils.Functions.GenUUID());
  142. }
  143. /// <summary>
  144. /// 生成任务id
  145. /// </summary>
  146. /// <param name="testId"></param>
  147. /// <param name="uuid"></param>
  148. /// <returns></returns>
  149. public static string GenTaskId(int testId, string uuid)
  150. {
  151. return $"{testId}_{uuid}";
  152. }
  153. /// <summary>
  154. /// 返回字符串右侧指定数量的字符串
  155. /// </summary>
  156. /// <param name="txt"></param>
  157. /// <param name="length"></param>
  158. /// <returns></returns>
  159. public static string RString(string txt, int length)
  160. {
  161. string res = string.Empty;
  162. if (!string.IsNullOrEmpty(txt))
  163. {
  164. res = length > txt.Length ? txt : txt.Substring(txt.Length - length);
  165. }
  166. return res;
  167. }
  168. /// <summary>
  169. /// 复制对象
  170. /// </summary>
  171. /// <typeparam name="TIn"></typeparam>
  172. /// <typeparam name="TOut"></typeparam>
  173. public static class CopyTo<TIn, TOut>
  174. {
  175. private static readonly Func<TIn, TOut> cache = GetFunc();
  176. private static Func<TIn, TOut> GetFunc()
  177. {
  178. ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
  179. List<MemberBinding> memberBindingList = new List<MemberBinding>();
  180. foreach (var item in typeof(TOut).GetProperties())
  181. {
  182. if (!item.CanWrite)
  183. continue;
  184. MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
  185. MemberBinding memberBinding = Expression.Bind(item, property);
  186. memberBindingList.Add(memberBinding);
  187. }
  188. MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
  189. Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
  190. return lambda.Compile();
  191. }
  192. public static TOut Trans(TIn tIn)
  193. {
  194. return cache(tIn);
  195. }
  196. }
  197. /// <summary>
  198. /// 获取时间戳 13位
  199. /// </summary>
  200. /// <returns></returns>
  201. public static long GetTimeStamp()
  202. {
  203. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  204. return Convert.ToInt64(ts.TotalSeconds * 1000);
  205. }
  206. /// <summary>
  207. /// 将时间戳转换为日期类型,并格式化
  208. /// </summary>
  209. /// <param name="longDateTime"></param>
  210. /// <returns></returns>
  211. public static string LongDateTimeToDateTimeString(string longDateTime)
  212. {
  213. //用来格式化long类型时间的,声明的变量
  214. long unixDate;
  215. DateTime start;
  216. DateTime date;
  217. //ENd
  218. unixDate = long.Parse(longDateTime);
  219. start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  220. date = start.AddMilliseconds(unixDate).ToLocalTime();
  221. return date.ToString("yyyy-MM-dd HH:mm:ss");
  222. }
  223. /// <summary>
  224. /// 获取制定路径文件的md5值
  225. /// </summary>
  226. /// <param name="filename"></param>
  227. /// <returns></returns>
  228. public static string FileMd5(string filename)
  229. {
  230. string res = "";
  231. try
  232. {
  233. using (FileStream file = new FileStream(filename, FileMode.Open))
  234. using (MD5 md5 = new MD5CryptoServiceProvider())
  235. {
  236. byte[] retVal = md5.ComputeHash(file);
  237. StringBuilder sb = new StringBuilder();
  238. for (int i = 0; i < retVal.Length; i++)
  239. {
  240. sb.Append(retVal[i].ToString("x2"));
  241. }
  242. res = sb.ToString();
  243. }
  244. }
  245. catch
  246. {
  247. }
  248. return res;
  249. }
  250. ///// <summary>
  251. ///// 生成上传文件对象的名称
  252. ///// </summary>
  253. ///// <param name="subjectId">科目id</param>
  254. ///// <param name="filename">文件名</param>
  255. ///// <returns></returns>
  256. //public static string GenUploadImageName(int subjectId, string filename)
  257. //{
  258. // string fileMd5 = FileMd5(filename), objectName = string.Empty;
  259. // if (!string.IsNullOrEmpty(fileMd5))
  260. // {
  261. // // 保存的文件名
  262. // objectName = $"images/marking/{Variables.Variables.SubjectIdCode[subjectId]}/{fileMd5.Substring(0, 4)}/{fileMd5}{Path.GetExtension(filename)}";
  263. // }
  264. // return objectName;
  265. //}
  266. ///// <summary>
  267. ///// 获得已使用的物理内存的大小,单位 (Byte),如果获取失败,返回 -1.
  268. ///// </summary>
  269. ///// <returns></returns>
  270. //public static double GetTotalPhysicalMemory(FileSizeUnit targetUnit = FileSizeUnit.MB)
  271. //{
  272. // long capacity = 0;
  273. // try
  274. // {
  275. // foreach (ManagementObject mo1 in new ManagementClass("Win32_PhysicalMemory").GetInstances().Cast<ManagementObject>())
  276. // {
  277. // capacity += long.Parse(mo1.Properties["Capacity"].Value.ToString());
  278. // }
  279. // }
  280. // catch (Exception ex)
  281. // {
  282. // capacity = -1;
  283. // Console.WriteLine(ex.Message);
  284. // }
  285. // return ToFileFormat(capacity, targetUnit);
  286. //}
  287. ///// <summary>
  288. ///// 获得已使用的物理内存的大小,单位 (Byte),如果获取失败,返回 -1.
  289. ///// </summary>
  290. ///// <returns></returns>
  291. //public static double GetAvailablePhysicalMemory(FileSizeUnit targetUnit = FileSizeUnit.MB)
  292. //{
  293. // long capacity = 0;
  294. // try
  295. // {
  296. // foreach (ManagementObject mo1 in new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory").GetInstances().Cast<ManagementObject>())
  297. // {
  298. // capacity += long.Parse(mo1.Properties["AvailableBytes"].Value.ToString());
  299. // }
  300. // }
  301. // catch (Exception ex)
  302. // {
  303. // capacity = -1;
  304. // Console.WriteLine(ex.Message);
  305. // }
  306. // return ToFileFormat(capacity, targetUnit);
  307. //}
  308. ///// <summary>
  309. ///// 根据指定的文件大小单位,对输入的文件大小(字节表示)进行转换。
  310. ///// </summary>
  311. ///// <param name="filesize">文件文件大小,单位为字节。</param>
  312. ///// <param name="targetUnit">目标单位。</param>
  313. ///// <returns></returns>
  314. //private static double ToFileFormat(long filesize, FileSizeUnit targetUnit = FileSizeUnit.MB)
  315. //{
  316. // double size;
  317. // switch (targetUnit)
  318. // {
  319. // case FileSizeUnit.KB: size = filesize / 1024.0; break;
  320. // case FileSizeUnit.MB: size = filesize / 1024.0 / 1024; break;
  321. // case FileSizeUnit.GB: size = filesize / 1024.0 / 1024 / 1024; break;
  322. // case FileSizeUnit.TB: size = filesize / 1024.0 / 1024 / 1024 / 1024; break;
  323. // case FileSizeUnit.PB: size = filesize / 1024.0 / 1024 / 1024 / 1024 / 1024; break;
  324. // default: size = filesize; break;
  325. // }
  326. // return size;
  327. //}
  328. ///// <summary>
  329. ///// 文件大小单位,包括从B至PB共六个单位。
  330. ///// </summary>
  331. //public enum FileSizeUnit
  332. //{
  333. // B,
  334. // KB,
  335. // MB,
  336. // GB,
  337. // TB,
  338. // PB
  339. //}
  340. }
  341. }