FileUtil.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using RevokeMsgPatcher.Model;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. namespace RevokeMsgPatcher.Utils
  8. {
  9. public class FileUtil
  10. {
  11. /// <summary>
  12. /// 获取文件版本
  13. /// </summary>
  14. /// <param name="path"></param>
  15. /// <returns></returns>
  16. public static string GetFileVersion(string path)
  17. {
  18. FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(path);
  19. return fileVersionInfo.FileVersion;
  20. }
  21. /// <summary>
  22. /// 计算文件SHA1
  23. /// </summary>
  24. /// <param name="s">文件路径</param>
  25. /// <returns></returns>
  26. public static string ComputeFileSHA1(string s)
  27. {
  28. FileStream file = new FileStream(s, FileMode.Open);
  29. SHA1 sha1 = new SHA1CryptoServiceProvider();
  30. byte[] retval = sha1.ComputeHash(file);
  31. file.Close();
  32. StringBuilder sc = new StringBuilder();
  33. for (int i = 0; i < retval.Length; i++)
  34. {
  35. sc.Append(retval[i].ToString("x2"));
  36. }
  37. return sc.ToString();
  38. }
  39. /// <summary>
  40. /// 修改文件指定位置的字节
  41. /// </summary>
  42. /// <param name="path">文件对象的路径</param>
  43. /// <param name="position">偏移位置</param>
  44. /// <param name="after">修改后的值</param>
  45. /// <returns></returns>
  46. public static bool EditHex(string path, long position, byte after)
  47. {
  48. using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
  49. {
  50. stream.Position = position;
  51. stream.WriteByte(after);
  52. }
  53. return true;
  54. }
  55. /// <summary>
  56. /// 修改文件多个指定位置的多个字节
  57. /// </summary>
  58. /// <param name="path">文件对象的路径</param>
  59. /// <param name="changes">需要修改的位置和内容</param>
  60. public static void EditMultiHex(string path, List<Change> changes)
  61. {
  62. using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
  63. {
  64. foreach (Change change in changes)
  65. {
  66. stream.Seek(change.Position, SeekOrigin.Begin);
  67. stream.Write(change.Content, 0, change.Content.Length);
  68. }
  69. }
  70. }
  71. }
  72. }