From 97d5dc9d1791b3ca0907b180e125d4decbd56ed6 Mon Sep 17 00:00:00 2001 From: HerobrineXia Date: Sat, 26 Sep 2026 18:53:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=A0=E7=94=A8=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E6=A3=80=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Shared/Utils/FileUtils.cs | 16 ++++++++++++++++ Tests/Utils/FileUtilsTest.cs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/Shared/Utils/FileUtils.cs b/Shared/Utils/FileUtils.cs index 38b05bc..b3dd7cb 100644 --- a/Shared/Utils/FileUtils.cs +++ b/Shared/Utils/FileUtils.cs @@ -461,6 +461,22 @@ public static class FileUtils { public static bool Exists(string filePath) => File.Exists(PathUtils.ForApi(filePath)); + /// + /// 检查文件是否未被其他进程占用 + /// 被占用或无权读取时返回 。 + /// + public static bool IsAvailable(string filePath) { + if (!Exists(filePath)) return true; + try { + Retrier.Attempt(maxAttempts: 3, delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => { + using var stream = new FileStream(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.None); + }); + return true; + } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { + return false; + } + } + /// /// 获取 对象。 /// diff --git a/Tests/Utils/FileUtilsTest.cs b/Tests/Utils/FileUtilsTest.cs index d8efd1c..472c9f8 100644 --- a/Tests/Utils/FileUtilsTest.cs +++ b/Tests/Utils/FileUtilsTest.cs @@ -1,6 +1,39 @@ namespace MeloongCore.Tests; public class FileUtilsTest : TestWithFolder { + [Test] + public async Task 文件可用性_只读与占用() { + string path = Path.Combine(tempFolder, "available.txt"); + await Assert.That(FileUtils.IsAvailable(path)).IsTrue(); + FileUtils.Write(path, "test"); + string apiPath = PathUtils.ForApi(path); + File.SetAttributes(apiPath, FileAttributes.ReadOnly); + try { + await Assert.That(FileUtils.IsAvailable(path)).IsTrue(); + await Assert.That((File.GetAttributes(apiPath) & FileAttributes.ReadOnly) != 0).IsTrue(); + } finally { + File.SetAttributes(apiPath, FileAttributes.Normal); + } + using (var stream = new FileStream(apiPath, FileMode.Open, FileAccess.Read, FileShare.None)) { + await Assert.That(FileUtils.IsAvailable(path)).IsFalse(); + } + await Assert.That(FileUtils.IsAvailable(path)).IsTrue(); + } + + [Test] + public async Task 文件可用性_短暂占用后重试() { + string path = Path.Combine(tempFolder, "temporary-lock.txt"); + FileUtils.Write(path, "test"); + using var stream = new FileStream(PathUtils.ForApi(path), FileMode.Open, FileAccess.Read, FileShare.None); + var release = Task.Run(async () => { + await Task.Delay(100); + stream.Dispose(); + }); + bool available = FileUtils.IsAvailable(path); + await release; + await Assert.That(available).IsTrue(); + } + #region 解压 [Test]