Explorar o código

ref: 迁移文件 Hash 计算

龙腾猫跃 hai 5 meses
pai
achega
f57f496d25
Modificáronse 2 ficheiros con 24 adicións e 1 borrados
  1. 2 1
      Shared/Utils/FileUtils.cs
  2. 22 0
      Shared/Utils/HashUtils.cs

+ 2 - 1
Shared/Utils/FileUtils.cs

@@ -9,7 +9,8 @@ public static class FileUtils {
     /// 打开指定文件的只读 <see cref="FileStream"/>。
     /// </summary>
     public static FileStream ReadAsStream(string filePath)
-        => new(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
+        => ResilientUtils.RetryOn<IOException, FileStream>(()
+            => new(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
 
     /// <summary>
     /// 读取文件中的所有内容。

+ 22 - 0
Shared/Utils/HashUtils.cs

@@ -0,0 +1,22 @@
+using System.Security.Cryptography;
+
+namespace MeloongCore;
+public static class HashUtils {
+    public enum HashMethod { Md5, Sha1, Sha256, Sha512 }
+
+    /// <summary>
+    /// 计算文件的哈希值(十六进制小写)。
+    /// </summary>
+    public static string ComputeFromFile(string filePath, HashMethod method) {
+        using var file = FileUtils.ReadAsStream(filePath);
+        using HashAlgorithm hashImpl = method switch {
+            HashMethod.Md5 => MD5.Create(),
+            HashMethod.Sha1 => SHA1.Create(),
+            HashMethod.Sha256 => SHA256.Create(),
+            HashMethod.Sha512 => SHA512.Create(),
+            _ => throw new ArgumentOutOfRangeException(nameof(method))
+        };
+        return BitConverter.ToString(hashImpl.ComputeHash(file)).Replace("-", "").ToLower();
+    }
+
+}