From 4f1664459df891aebb16e49c49a1839572331746 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: Fri, 8 May 2026 21:27:04 +0800
Subject: [PATCH] PathUtils.RemoveLastPart
---
Shared/Extensions/StringExtensions.cs | 8 ++++----
Shared/General/MsDelta.cs | 4 ++--
Shared/Utils/DirectoryUtils.cs | 3 +--
Shared/Utils/FileUtils.cs | 13 +++++++------
Shared/Utils/PathUtils.cs | 24 ++++++++++++++++--------
Tests/Utils/FileUtilsTest.cs | 8 ++++----
Tests/Utils/PathUtilsTest.cs | 20 ++++++++++++++++++++
7 files changed, 54 insertions(+), 26 deletions(-)
create mode 100644 Tests/Utils/PathUtilsTest.cs
diff --git a/Shared/Extensions/StringExtensions.cs b/Shared/Extensions/StringExtensions.cs
index fa5e5c2..faacdb5 100644
--- a/Shared/Extensions/StringExtensions.cs
+++ b/Shared/Extensions/StringExtensions.cs
@@ -98,7 +98,7 @@ public static class StringExtensions {
/// "2024/11/08".BeforeFirst("/") => "2024"
///
public static string BeforeFirst(this string str, string text, bool ignoreCase = false) {
- int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
+ int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
if (pos < 0) return str;
return str.Substring(0, pos);
}
@@ -107,7 +107,7 @@ public static class StringExtensions {
/// "2024/11/08".BeforeLast("/") => "2024/11"
///
public static string BeforeLast(this string str, string text, bool ignoreCase = false) {
- int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
+ int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
if (pos < 0) return str;
return str.Substring(0, pos);
}
@@ -117,7 +117,7 @@ public static class StringExtensions {
/// "2024/11/08".AfterFirst("/") => "11/08"
///
public static string AfterFirst(this string str, string text, bool ignoreCase = false) {
- int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text!, ignoreCase);
+ int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
if (pos < 0) return str;
return str.Substring(pos + text!.Length);
}
@@ -126,7 +126,7 @@ public static class StringExtensions {
/// "2024/11/08".AfterLast("/") => "08"
///
public static string AfterLast(this string str, string text, bool ignoreCase = false) {
- int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase);
+ int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
if (pos < 0) return str;
return str.Substring(pos + text!.Length);
}
diff --git a/Shared/General/MsDelta.cs b/Shared/General/MsDelta.cs
index 5b4417b..3333641 100644
--- a/Shared/General/MsDelta.cs
+++ b/Shared/General/MsDelta.cs
@@ -15,7 +15,7 @@ public static class MsDelta {
public static void Create(string oldFilePath, string newFilePath, string deltaFilePath) {
if (!FileUtils.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath);
if (!FileUtils.Exists(newFilePath)) throw new FileNotFoundException($"新文件不存在:{newFilePath}", newFilePath);
- DirectoryUtils.Create(deltaFilePath, isFilePath: true);
+ DirectoryUtils.Create(PathUtils.RemoveLastPart(deltaFilePath));
Logger.Info($"正在生成补丁:{oldFilePath} → {newFilePath},补丁文件将输出到:{deltaFilePath}");
// fileTypeSet:https://learn.microsoft.com/en-us/previous-versions/bb417345(v=msdn.10)?redirectedfrom=MSDN#file-type-sets (15L: DELTA_FILE_TYPE_SET_EXECUTABLES)
// 131072L: IgnoreFileSizeLimit, 32u: Crc32
@@ -32,7 +32,7 @@ public static class MsDelta {
public static void Apply(string oldFilePath, string deltaFilePath, string newFilePath) {
if (!FileUtils.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath);
if (!FileUtils.Exists(deltaFilePath)) throw new FileNotFoundException($"补丁文件不存在:{deltaFilePath}", deltaFilePath);
- DirectoryUtils.Create(newFilePath, isFilePath: true);
+ DirectoryUtils.Create(PathUtils.RemoveLastPart(newFilePath));
Logger.Info($"正在应用补丁:原始文件 {oldFilePath} + 补丁文件 {deltaFilePath} → 输出至 {newFilePath}");
// 1L: AllowLegacy
if (!ApplyDelta(1L, PathUtils.WithLongPath(oldFilePath), PathUtils.WithLongPath(deltaFilePath), PathUtils.WithLongPath(newFilePath)))
diff --git a/Shared/Utils/DirectoryUtils.cs b/Shared/Utils/DirectoryUtils.cs
index 36937b3..1708986 100644
--- a/Shared/Utils/DirectoryUtils.cs
+++ b/Shared/Utils/DirectoryUtils.cs
@@ -5,8 +5,7 @@ public static class DirectoryUtils {
/// 创建文件夹,或文件所在的文件夹。
/// 文件夹已存在时不会抛出异常。
///
- public static void Create(string path, bool isFilePath = false) {
- if (isFilePath) path = PathUtils.RemoveFileName(path);
+ public static void Create(string path) {
if (DirectoryUtils.Exists(path)) return;
Logger.Trace($"新建文件夹:{path}");
path = PathUtils.WithLongPath(path);
diff --git a/Shared/Utils/FileUtils.cs b/Shared/Utils/FileUtils.cs
index dcef143..70935c5 100644
--- a/Shared/Utils/FileUtils.cs
+++ b/Shared/Utils/FileUtils.cs
@@ -68,7 +68,7 @@ public static class FileUtils {
/// 若文件已存在,则会覆盖原文件。
///
public static void Write(string filePath, byte[] content) {
- DirectoryUtils.Create(filePath, isFilePath: true);
+ DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
Logger.Trace($"写入文件:{filePath}({content.Length} 字节)");
ResilientUtils.RetryOn(()
=> File.WriteAllBytes(PathUtils.WithLongPath(filePath), content));
@@ -90,7 +90,7 @@ public static class FileUtils {
/// 若文件已存在,则会覆盖原文件。
///
public static FileStream CreateAsStream(string filePath) {
- DirectoryUtils.Create(filePath, isFilePath: true);
+ DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
Logger.Trace($"创建文件流:{filePath}");
return ResilientUtils.RetryOn(()
=> new FileStream(PathUtils.WithLongPath(filePath), FileMode.Create));
@@ -111,7 +111,7 @@ public static class FileUtils {
Logger.Info($"尝试复制文件,但原文件不存在,已跳过复制:{sourceFilePath} → {destFilePath}");
return;
}
- DirectoryUtils.Create(destFilePath, isFilePath: true);
+ DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
Logger.Trace($"复制文件:{sourceFilePath} → {destFilePath}");
ResilientUtils.RetryOn(()
=> File.Copy(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath), true));
@@ -123,7 +123,7 @@ public static class FileUtils {
///
public static void Move(string sourceFilePath, string destFilePath) {
if (sourceFilePath == destFilePath) return; // 如果移动同一个文件则跳过
- DirectoryUtils.Create(destFilePath, isFilePath: true);
+ DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
FileUtils.Delete(destFilePath);
Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}");
ResilientUtils.RetryOn(()
@@ -265,6 +265,7 @@ public static class FileUtils {
using var fileStream = FileUtils.ReadAsStream(compressionFile);
using var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress);
FileUtils.Write(outFilePath, gzipStream);
+ progressHandler?.Invoke(1);
return;
}
// 解压 zip
@@ -294,7 +295,7 @@ public static class FileUtils {
public static void CreateZipFromDirectory(string outputFullPath, string sourceDirectory) {
outputFullPath = PathUtils.WithLongPath(outputFullPath);
sourceDirectory = PathUtils.WithLongPath(sourceDirectory);
- DirectoryUtils.Create(outputFullPath, isFilePath: true);
+ DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
FileUtils.Delete(outputFullPath);
Logger.Trace($"将文件夹中的内容压缩为 zip 文件:{sourceDirectory} → {outputFullPath}");
ResilientUtils.RetryOn(()
@@ -322,7 +323,7 @@ public static class FileUtils {
/// 键为 zip 文件下的路径,值为文件的本地路径。
public static void CreateZipFromFiles(string outputFullPath, IDictionary sources) {
outputFullPath = PathUtils.WithLongPath(outputFullPath);
- DirectoryUtils.Create(outputFullPath, isFilePath: true);
+ DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
FileUtils.Delete(outputFullPath);
using var archive = ResilientUtils.RetryOn(()
=> ZipFile.Open(outputFullPath, ZipArchiveMode.Create));
diff --git a/Shared/Utils/PathUtils.cs b/Shared/Utils/PathUtils.cs
index 9d21569..c17705d 100644
--- a/Shared/Utils/PathUtils.cs
+++ b/Shared/Utils/PathUtils.cs
@@ -34,7 +34,7 @@ public static class PathUtils {
if (fullName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
if (keepFileName && FileUtils.Exists(fullName)) {
pathToKeep = Path.GetFileName(fullName);
- pathToShorten = PathUtils.RemoveFileName(fullName);
+ pathToShorten = PathUtils.RemoveLastPart(fullName);
}
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
@@ -85,13 +85,21 @@ public static class PathUtils {
#region 路径处理
///
- /// 去除路径末尾的文件名。
- /// 若路径以分隔符结尾,则不作处理。
- ///
- public static string RemoveFileName(string? path) {
- if (path is null || string.IsNullOrEmpty(path)) return "";
- if (path.EndsWithF(Path.DirectorySeparatorChar) || path.EndsWithF(Path.AltDirectorySeparatorChar)) return path;
- return Path.GetDirectoryName(path) ?? "";
+ /// 去除路径的最后一级,并移除末尾的分隔符。
+ ///
+ /// "C:\foo\bar.txt" → "C:\foo"
+ /// "C:\foo\bar" → "C:\foo"
+ /// "C:\foo\bar\" → "C:\foo"
+ /// "C:\foo\" → "C:"
+ /// "https://foo.bar/file/pack.zip?arg=1" → "https://foo.bar/file"
+ ///
+ public static string RemoveLastPart(string? path) {
+ if (path!.Contains("://")) { // 网络路径
+ path = PathUtils.WithoutSeparator(path.BeforeFirst("#").BeforeFirst("?")); // 去除参数
+ return PathUtils.WithoutSeparator(path).BeforeLast("/");
+ } else { // 文件路径
+ return PathUtils.WithoutSeparator(path!).BeforeLast("\\");
+ }
}
///
diff --git a/Tests/Utils/FileUtilsTest.cs b/Tests/Utils/FileUtilsTest.cs
index 1013670..036729d 100644
--- a/Tests/Utils/FileUtilsTest.cs
+++ b/Tests/Utils/FileUtilsTest.cs
@@ -6,7 +6,7 @@ public class FileUtilsTest : TestWithFolder {
[Theory]
[InlineData("GB Encoding.zip")]
[InlineData("UTF8 Encoding.zip")]
- public void Compression_ReadZip(string testFile) {
+ public void 压缩包_ReadZip(string testFile) {
double progress = 0;
string output = Path.Combine(tempFolder, "Extracted");
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p);
@@ -19,7 +19,7 @@ public class FileUtilsTest : TestWithFolder {
[Theory]
[InlineData("GZ.gz", "LTCat")]
- public void Compression_ReadGz(string testFile, string containsText) {
+ public void 压缩包_ReadGz(string testFile, string containsText) {
double progress = 0;
string output = Path.Combine(tempFolder, "Extracted");
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p);
@@ -30,14 +30,14 @@ public class FileUtilsTest : TestWithFolder {
[Theory]
[InlineData("Corrupted.zip")]
[InlineData("Not zip.zip")]
- public void Compression_ReadBad(string testFile) {
+ public void 压缩包_ReadBad(string testFile) {
Assert.Throws(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder));
}
[Theory]
[InlineData("DotDot ZipSlip.zip")]
[InlineData("AbsPath ZipSlip.zip")]
- public void Compression_ZipSlip(string testFile) {
+ public void 压缩包_ZipSlip(string testFile) {
Assert.Throws(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder));
}
diff --git a/Tests/Utils/PathUtilsTest.cs b/Tests/Utils/PathUtilsTest.cs
new file mode 100644
index 0000000..20853e5
--- /dev/null
+++ b/Tests/Utils/PathUtilsTest.cs
@@ -0,0 +1,20 @@
+namespace MeloongCore.Tests;
+public class PathUtilsTests {
+
+ [Theory]
+ [InlineData(@"\\?\C:\foo\bar.txt", @"\\?\C:\foo")]
+ [InlineData(@"C:\foo\bar.txt", @"C:\foo")]
+ [InlineData(@"\\?\C:\foo\bar", @"\\?\C:\foo")]
+ [InlineData(@"C:\foo\bar", @"C:\foo")]
+ [InlineData(@"C:\foo\bar\", @"C:\foo")]
+ [InlineData(@"\\?\C:\foo\", @"\\?\C:")]
+ [InlineData(@"C:\foo", @"C:")]
+ [InlineData(@"C:\foo\", @"C:")]
+ [InlineData("https://foo.bar/file/long/pack.zip?arg=1", "https://foo.bar/file/long")]
+ [InlineData("https://foo.bar/file/", "https://foo.bar")]
+ [InlineData("https://foo.bar/file/?arg=1", "https://foo.bar")]
+ [InlineData("https://foo.bar/file?arg=1", "https://foo.bar")]
+ public void 路径处理_RemoveLastPart(string? input, string expected)
+ => Assert.Equal(expected, PathUtils.RemoveLastPart(input));
+
+}
\ No newline at end of file