Functions.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. using System.Threading;
  10. namespace DaJiaoYan.Utils
  11. {
  12. internal class Functions
  13. {
  14. private static readonly Queue<string> Pool = new Queue<string>();
  15. private static readonly object _UUIDLocker = new object();
  16. /// <summary>
  17. /// 字符串生成MD5
  18. /// </summary>
  19. /// <param name="s"></param>
  20. /// <returns></returns>
  21. public static string GenMd5(string s)
  22. {
  23. //就是比string往后一直加要好的优化容器
  24. StringBuilder sb = new StringBuilder();
  25. using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
  26. {
  27. //将输入字符串转换为字节数组并计算哈希。
  28. byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(s));
  29. //X为 十六进制 X都是大写 x都为小写
  30. //2为 每次都是两位数
  31. //假设有两个数10和26,正常情况十六进制显示0xA、0x1A,这样看起来不整齐,为了好看,可以指定"X2",这样显示出来就是:0x0A、0x1A。
  32. //遍历哈希数据的每个字节
  33. //并将每个字符串格式化为十六进制字符串。
  34. int length = data.Length;
  35. for (int i = 0; i < length; i++)
  36. {
  37. sb.Append(data[i].ToString("X2"));
  38. }
  39. }
  40. return sb.ToString();
  41. }
  42. /// <summary>
  43. /// 获取文件的MD5码
  44. /// </summary>
  45. /// <param name="fileName">传入的文件名(含路径及后缀名)</param>
  46. /// <returns></returns>
  47. /// <exception cref="Exception"></exception>
  48. public static string GenMd5HashFromFile(string fileName)
  49. {
  50. try
  51. {
  52. StringBuilder sb = new StringBuilder();
  53. using (MD5 md5 = new MD5CryptoServiceProvider())
  54. using (FileStream file = new FileStream(fileName, FileMode.Open))
  55. {
  56. byte[] retVal = md5.ComputeHash(file);
  57. //file.Close();
  58. for (int i = 0; i < retVal.Length; i++)
  59. {
  60. sb.Append(retVal[i].ToString("X2"));
  61. }
  62. }
  63. return sb.ToString();
  64. }
  65. catch (Exception ex)
  66. {
  67. throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
  68. }
  69. }
  70. private static void UUIDInit()
  71. {
  72. lock (_UUIDLocker)
  73. {
  74. for (int i = 0; i < 10000; i++)
  75. {
  76. Pool.Enqueue(Guid.NewGuid().ToString("N"));
  77. Thread.Sleep(1);
  78. }
  79. }
  80. }
  81. /// <summary>
  82. /// UUID生成程序
  83. /// </summary>
  84. public static void UUIDBackgroundFunc()
  85. {
  86. new Thread(() =>
  87. {
  88. while (true)
  89. {
  90. if (Pool.Count < 5000)
  91. {
  92. UUIDInit();
  93. }
  94. Thread.Sleep(1000);
  95. }
  96. })
  97. {
  98. IsBackground = true
  99. }.Start();
  100. }
  101. /// <summary>
  102. /// 生成UUID
  103. /// </summary>
  104. /// <returns></returns>
  105. public static string GenUUID()
  106. {
  107. //if (Pool.Count <= 100)
  108. //{
  109. // UUIDInit();
  110. //}
  111. return Pool.Dequeue();
  112. }
  113. /// <summary>
  114. /// 深复制对象
  115. /// </summary>
  116. /// <typeparam name="T"></typeparam>
  117. /// <param name="source"></param>
  118. /// <returns></returns>
  119. /// <exception cref="ArgumentException"></exception>
  120. public static T Clone<T>(T source)
  121. {
  122. if (!typeof(T).IsSerializable)
  123. {
  124. throw new ArgumentException("The type must be serializable.", "source");
  125. }
  126. // Don't serialize a null object, simply return the default for that object
  127. if (source == null)
  128. {
  129. return default;
  130. }
  131. IFormatter formatter = new BinaryFormatter();
  132. //Stream stream = new MemoryStream();
  133. using (Stream stream = new MemoryStream())
  134. {
  135. formatter.Serialize(stream, source);
  136. stream.Seek(0, SeekOrigin.Begin);
  137. return (T)formatter.Deserialize(stream);
  138. }
  139. }
  140. /// <summary>
  141. /// 返回字符串右侧指定数量的字符串
  142. /// </summary>
  143. /// <param name="txt"></param>
  144. /// <param name="length"></param>
  145. /// <returns></returns>
  146. public static string RString(string txt, int length)
  147. {
  148. string res = string.Empty;
  149. if (!string.IsNullOrEmpty(txt))
  150. {
  151. res = length > txt.Length ? txt : txt.Substring(txt.Length - length);
  152. }
  153. return res;
  154. }
  155. /// <summary>
  156. /// 复制对象
  157. /// </summary>
  158. /// <typeparam name="TIn"></typeparam>
  159. /// <typeparam name="TOut"></typeparam>
  160. public static class CopyTo<TIn, TOut>
  161. {
  162. private static readonly Func<TIn, TOut> cache = GetFunc();
  163. private static Func<TIn, TOut> GetFunc()
  164. {
  165. ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
  166. List<MemberBinding> memberBindingList = new List<MemberBinding>();
  167. foreach (var item in typeof(TOut).GetProperties())
  168. {
  169. if (!item.CanWrite)
  170. continue;
  171. MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
  172. MemberBinding memberBinding = Expression.Bind(item, property);
  173. memberBindingList.Add(memberBinding);
  174. }
  175. MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
  176. Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
  177. return lambda.Compile();
  178. }
  179. public static TOut Trans(TIn tIn)
  180. {
  181. return cache(tIn);
  182. }
  183. }
  184. /// <summary>
  185. /// 获取时间戳 13位
  186. /// </summary>
  187. /// <returns></returns>
  188. public static long GetTimeStamp()
  189. {
  190. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  191. return Convert.ToInt64(ts.TotalSeconds * 1000);
  192. }
  193. /// <summary>
  194. /// 将时间戳转换为日期类型,并格式化
  195. /// </summary>
  196. /// <param name="longDateTime"></param>
  197. /// <returns></returns>
  198. public static string LongDateTimeToDateTimeString(string longDateTime)
  199. {
  200. //用来格式化long类型时间的,声明的变量
  201. long unixDate;
  202. DateTime start;
  203. DateTime date;
  204. //ENd
  205. unixDate = long.Parse(longDateTime);
  206. start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  207. date = start.AddMilliseconds(unixDate).ToLocalTime();
  208. return date.ToString("yyyy-MM-dd HH:mm:ss");
  209. }
  210. /// <summary>
  211. /// 获取制定路径文件的md5值
  212. /// </summary>
  213. /// <param name="filename"></param>
  214. /// <returns></returns>
  215. public static string FileMd5(string filename)
  216. {
  217. string res = "";
  218. try
  219. {
  220. using (FileStream file = new FileStream(filename, FileMode.Open))
  221. using (MD5 md5 = new MD5CryptoServiceProvider())
  222. {
  223. byte[] retVal = md5.ComputeHash(file);
  224. StringBuilder sb = new StringBuilder();
  225. for (int i = 0; i < retVal.Length; i++)
  226. {
  227. sb.Append(retVal[i].ToString("x2"));
  228. }
  229. res = sb.ToString();
  230. }
  231. }
  232. catch
  233. {
  234. }
  235. return res;
  236. }
  237. /// <summary>
  238. /// 上传的原始图片地址
  239. /// </summary>
  240. /// <param name="testId"></param>
  241. /// <param name="campusId"></param>
  242. /// <param name="filename"></param>
  243. /// <returns></returns>
  244. public static string GenUploadOriginImageName(int testId, int campusId, string filename, string batchId = null)
  245. {
  246. string res;
  247. if (string.IsNullOrEmpty(batchId))
  248. {
  249. res = $"origin/{testId}/{campusId}/{Path.GetFileName(filename)}";
  250. }
  251. else
  252. {
  253. res = $"origin/{testId}/{campusId}/{batchId}/{Path.GetFileName(filename)}";
  254. }
  255. return res;
  256. }
  257. public static long GetHardDiskSpace(string str_HardDiskName)
  258. {
  259. long totalSize = 0;
  260. str_HardDiskName += ":\\";
  261. System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
  262. foreach (System.IO.DriveInfo drive in drives)
  263. {
  264. if (string.Equals(drive.Name, str_HardDiskName, StringComparison.OrdinalIgnoreCase))
  265. {
  266. totalSize = drive.TotalFreeSpace;
  267. }
  268. }
  269. return totalSize;
  270. }
  271. public static string GetHardDiskFreeSpace(string str_HardDiskFreeSpace, FileSizeUnit targetUnit = FileSizeUnit.MB)
  272. {
  273. long totalSize = GetHardDiskSpace(str_HardDiskFreeSpace);
  274. return Math.Floor(ToFileFormat(totalSize, targetUnit)).ToString() + Enum.GetName(typeof(FileSizeUnit), targetUnit);
  275. }
  276. /// <summary>
  277. /// 根据指定的文件大小单位,对输入的文件大小(字节表示)进行转换。
  278. /// </summary>
  279. /// <param name="filesize">文件文件大小,单位为字节。</param>
  280. /// <param name="targetUnit">目标单位。</param>
  281. /// <returns></returns>
  282. private static double ToFileFormat(long filesize, FileSizeUnit targetUnit = FileSizeUnit.MB)
  283. {
  284. double size;
  285. switch (targetUnit)
  286. {
  287. case FileSizeUnit.KB: size = filesize / 1024.0; break;
  288. case FileSizeUnit.MB: size = filesize / 1024.0 / 1024; break;
  289. case FileSizeUnit.GB: size = filesize / 1024.0 / 1024 / 1024; break;
  290. case FileSizeUnit.TB: size = filesize / 1024.0 / 1024 / 1024 / 1024; break;
  291. case FileSizeUnit.PB: size = filesize / 1024.0 / 1024 / 1024 / 1024 / 1024; break;
  292. default: size = filesize; break;
  293. }
  294. return size;
  295. }
  296. /// <summary>
  297. /// 文件大小单位,包括从B至PB共六个单位。
  298. /// </summary>
  299. public enum FileSizeUnit
  300. {
  301. B,
  302. KB,
  303. MB,
  304. GB,
  305. TB,
  306. PB
  307. }
  308. }
  309. }