FileExtensions.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using System.IO;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. namespace Update.Utils
  5. {
  6. public static class FileExtensions
  7. {
  8. /// <summary>
  9. /// 生成文件的md5
  10. /// </summary>
  11. /// <param name="filename"></param>
  12. /// <returns></returns>
  13. private static string FilenameMutexKey(string filename)
  14. {
  15. return Functions.GenMd5(filename);
  16. }
  17. /// <summary>
  18. /// 写入二进制值
  19. /// </summary>
  20. /// <param name="filename"></param>
  21. /// <param name="bytes"></param>
  22. public static void WriteBytes(string filename, byte[] bytes)
  23. {
  24. if (bytes != null)
  25. {
  26. string key = FilenameMutexKey(filename);
  27. CheckDirectory(Path.GetDirectoryName(filename), true);
  28. void act()
  29. {
  30. File.WriteAllBytes(filename, bytes);
  31. }
  32. MutexExtensions.Exec(key, act);
  33. }
  34. }
  35. /// <summary>
  36. /// 添加所有文本
  37. /// </summary>
  38. /// <param name="filename"></param>
  39. /// <param name="txt"></param>
  40. /// <param name="encoding"></param>
  41. public static void AppendAllText(string filename, string txt, Encoding encoding = null)
  42. {
  43. encoding = encoding ?? Encoding.UTF8;
  44. string key = FilenameMutexKey(filename);
  45. CheckDirectory(Path.GetDirectoryName(filename), true);
  46. void act()
  47. {
  48. File.AppendAllText(filename, txt, encoding);
  49. }
  50. MutexExtensions.Exec(key, act);
  51. }
  52. /// <summary>
  53. /// 检查目录是否存在,如果不存在,将根据条件创建或不创建
  54. /// </summary>
  55. /// <param name="p"></param>
  56. /// <param name="create">如果目录不存在,是否创建</param>
  57. /// <returns></returns>
  58. public static bool CheckDirectory(string p, bool create)
  59. {
  60. bool res = false;
  61. if (!string.IsNullOrEmpty(p))
  62. {
  63. res = Directory.Exists(p);
  64. if (!res && create)
  65. {
  66. Directory.CreateDirectory(p);
  67. res = true;
  68. }
  69. }
  70. return res;
  71. }
  72. /// <summary>
  73. /// 获取制定路径文件的md5值
  74. /// </summary>
  75. /// <param name="filename"></param>
  76. /// <returns></returns>
  77. public static string FileMd5(string filename)
  78. {
  79. string res = "";
  80. try
  81. {
  82. using (FileStream file = new FileStream(filename, FileMode.Open))
  83. using (MD5 md5 = new MD5CryptoServiceProvider())
  84. {
  85. byte[] retVal = md5.ComputeHash(file);
  86. StringBuilder sb = new StringBuilder();
  87. for (int i = 0; i < retVal.Length; i++)
  88. {
  89. sb.Append(retVal[i].ToString("x2"));
  90. }
  91. res = sb.ToString();
  92. }
  93. }
  94. catch
  95. {
  96. }
  97. return res;
  98. }
  99. }
  100. }