From f57f496d25b7527a7937a6c115a37702fd93c83e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=BE=99=E8=85=BE=E7=8C=AB=E8=B7=83?= <1043137532@qq.com>
Date: Tue, 12 May 2026 19:31:36 +0800
Subject: [PATCH] =?UTF-8?q?ref:=20=E8=BF=81=E7=A7=BB=E6=96=87=E4=BB=B6=20H?=
=?UTF-8?q?ash=20=E8=AE=A1=E7=AE=97?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Shared/Utils/FileUtils.cs | 3 ++-
Shared/Utils/HashUtils.cs | 22 ++++++++++++++++++++++
2 files changed, 24 insertions(+), 1 deletion(-)
create mode 100644 Shared/Utils/HashUtils.cs
diff --git a/Shared/Utils/FileUtils.cs b/Shared/Utils/FileUtils.cs
index b74f4f9..45a328c 100644
--- a/Shared/Utils/FileUtils.cs
+++ b/Shared/Utils/FileUtils.cs
@@ -9,7 +9,8 @@ public static class FileUtils {
/// 打开指定文件的只读 。
///
public static FileStream ReadAsStream(string filePath)
- => new(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
+ => ResilientUtils.RetryOn(()
+ => new(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
///
/// 读取文件中的所有内容。
diff --git a/Shared/Utils/HashUtils.cs b/Shared/Utils/HashUtils.cs
new file mode 100644
index 0000000..00361d7
--- /dev/null
+++ b/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 }
+
+ ///
+ /// 计算文件的哈希值(十六进制小写)。
+ ///
+ 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();
+ }
+
+}