10 Commits
10 changed files with 294 additions and 104 deletions

No files matched your search

+8 -3
View File
@@ -39,16 +39,21 @@ public static class ExceptionExtensions {
// 提取堆栈信息
var lines = new List<string>();
bool isInnerException = false;
static string getExceptionMessage(Exception e) => e.Message + (e switch {
WebException webEx => $" (Status={webEx.Status})",
SocketException socketEx => $" (SocketErrorCode={socketEx.SocketErrorCode})",
_ => ""
});
foreach (var currentEx in ex.Flatten()) {
if (showMultilineStacks) {
lines.Add((isInnerException ? "→ " : "") + currentEx.Message.ReplaceLineEndings("\r\n", true));
lines.Add((isInnerException ? "→ " : "") + getExceptionMessage(currentEx).ReplaceLineEndings("\r\n", true));
var stackLines = (currentEx.StackTrace?.SplitLines(true) ?? [])
.Select(l => l.BeforeLast("(") + l.AfterLast(")"))
.Distinct();
lines.AddRange(stackLines);
if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName);
} else {
lines.Add(currentEx.Message.ReplaceLineEndings(" ", true));
lines.Add(getExceptionMessage(currentEx).ReplaceLineEndings(" ", true));
}
isInnerException = true;
}
@@ -104,7 +109,7 @@ public static class ExceptionExtensions {
}
if (webEx.Status is WebExceptionStatus.NameResolutionFailure or WebExceptionStatus.ConnectFailure or WebExceptionStatus.ReceiveFailure or
WebExceptionStatus.SendFailure or WebExceptionStatus.ConnectionClosed or WebExceptionStatus.KeepAliveFailure or WebExceptionStatus.Timeout or
WebExceptionStatus.ProxyNameResolutionFailure) return true;
WebExceptionStatus.ProxyNameResolutionFailure or WebExceptionStatus.SecureChannelFailure) return true;
} else if (currentEx is SocketException socketEx) {
if (socketEx.SocketErrorCode is SocketError.NetworkDown or SocketError.NetworkUnreachable or SocketError.NetworkReset or SocketError.ConnectionAborted or
SocketError.ConnectionReset or SocketError.TimedOut or SocketError.ConnectionRefused or SocketError.HostUnreachable or
+21 -13
View File
@@ -1,5 +1,4 @@
using System.Text.RegularExpressions;
using static System.Net.Mime.MediaTypeNames;
namespace MeloongCore.Extensions;
public static class StringExtensions {
@@ -129,7 +128,7 @@ public static class StringExtensions {
public static string BeforeFirst(this string str, string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
if (pos < 0) return str;
return str.Substring(0, pos);
return str[..pos];
}
/// <summary>
/// 获取在任意子字符串第一次出现之前的部分,如果未找到任意子字符串则不裁切。
@@ -144,7 +143,7 @@ public static class StringExtensions {
if (p >= 0 && (pos < 0 || pos > p)) pos = p;
}
if (pos < 0) return str;
return str.Substring(0, pos);
return str[..pos];
}
/// <summary>
@@ -154,7 +153,7 @@ public static class StringExtensions {
public static string BeforeLast(this string str, string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
if (pos < 0) return str;
return str.Substring(0, pos);
return str[..pos];
}
/// <summary>
/// 获取在任意子字符串最后一次出现之前的部分,如果未找到任意子字符串则不裁切。
@@ -169,7 +168,7 @@ public static class StringExtensions {
if (p >= 0 && (pos < 0 || pos < p)) pos = p;
}
if (pos < 0) return str;
return str.Substring(0, pos);
return str[..pos];
}
/// <summary>
@@ -179,7 +178,7 @@ public static class StringExtensions {
public static string AfterFirst(this string str, string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.IndexOfF(text, ignoreCase);
if (pos < 0) return str;
return str.Substring(pos + text!.Length);
return str[(pos + text!.Length)..];
}
/// <summary>
/// 获取在任意子字符串第一次出现之后的部分,如果未找到任意子字符串则不裁切。
@@ -198,7 +197,7 @@ public static class StringExtensions {
}
}
if (pos < 0) return str;
return str.Substring(pos + len);
return str[(pos + len)..];
}
/// <summary>
@@ -208,7 +207,7 @@ public static class StringExtensions {
public static string AfterLast(this string str, string text, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text, ignoreCase);
if (pos < 0) return str;
return str.Substring(pos + text!.Length);
return str[(pos + text!.Length)..];
}
/// <summary>
/// 获取在任意子字符串最后一次出现之后的部分,如果未找到任意子字符串则不裁切。
@@ -227,7 +226,7 @@ public static class StringExtensions {
}
}
if (pos < 0) return str;
return str.Substring(pos + len);
return str[(pos + len)..];
}
/// <summary>
@@ -245,9 +244,9 @@ public static class StringExtensions {
int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase);
if (endPos >= 0) {
return str.Substring(startPos, endPos - startPos);
return str[startPos..endPos];
} else if (startPos > 0) {
return str.Substring(startPos);
return str[startPos..];
} else {
return str;
}
@@ -374,7 +373,7 @@ public static class StringExtensions {
/// </summary>
public static string Capitalize(this string word) {
if (string.IsNullOrEmpty(word)) return word;
return $"{word.Substring(0, 1).Upper()}{word.Substring(1).Lower()}";
return $"{word[..1].Upper()}{word[1..].Lower()}";
}
/// <summary>
@@ -383,7 +382,7 @@ public static class StringExtensions {
/// </summary>
public static string EnsureLength(this string? str, char code, int length) {
str ??= "";
return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code);
return str.Length > length ? str[..length] : str.PadLeft(length, code);
}
/// <summary>
@@ -392,4 +391,13 @@ public static class StringExtensions {
public static bool IsAsciiOnly(this string input)
=> input.All(c => c < 128);
/// <summary>
/// 计算字符串的哈希,其结果在不同环境中均能保持一致。
/// </summary>
public static ulong GetStableHashCode(this string str) {
ulong result = 5381;
foreach (char v in str) result = (result << 5) ^ result ^ v;
return result ^ 0xA98F501BC684032FUL;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
public static class Main {
public static void Init(BaseLogger? logger = null) {
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(2));
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(5));
if (logger != null) Logger.Instance = logger;
}
+139
View File
@@ -0,0 +1,139 @@
using System.Security;
using System.Security.Cryptography;
namespace MeloongCore;
public static class CryptographyUtils {
#region Hash
public enum HashMethod {
/// <summary>
/// 使用 <see cref="MD5"/> 算法。在 16 进制下哈希为 32 长度字符串。
/// </summary>
Md5,
/// <summary>
/// 使用 <see cref="SHA1"/> 算法。在 16 进制下哈希为 40 长度字符串。
/// </summary>
Sha1,
/// <summary>
/// 使用 <see cref="SHA256"/> 算法。在 16 进制下哈希为 64 长度字符串。
/// </summary>
Sha256,
/// <summary>
/// 使用 <see cref="SHA512"/> 算法。在 16 进制下哈希为 128 长度字符串。
/// </summary>
Sha512
}
private static HashAlgorithm GetHashAlgorithm(HashMethod method) => method switch {
HashMethod.Md5 => MD5.Create(),
HashMethod.Sha1 => SHA1.Create(),
HashMethod.Sha256 => SHA256.Create(),
HashMethod.Sha512 => SHA512.Create(),
_ => throw new ArgumentOutOfRangeException(nameof(method))
};
/// <summary>
/// 计算文件的 Hash。返回 16 进制小写字符串。
/// </summary>
public static string ComputeFileHash(string filePath, HashMethod method = HashMethod.Md5) {
using HashAlgorithm hashImpl = GetHashAlgorithm(method);
Logger.Trace($"计算文件 {method}:{filePath}");
using var file = FileUtils.ReadAsStream(filePath);
return BitConverter.ToString(hashImpl.ComputeHash(file)).Replace("-", "").Lower();
}
/// <summary>
/// 计算字节数组的 Hash。返回 16 进制小写字符串。
/// </summary>
public static string ComputeHash(byte[] input, HashMethod method = HashMethod.Md5) {
using HashAlgorithm hashImpl = GetHashAlgorithm(method);
return BitConverter.ToString(hashImpl.ComputeHash(input)).Replace("-", "").Lower();
}
/// <summary>
/// 计算字符串的 Hash。返回 16 进制小写字符串。
/// <para/> 使用 UTF-8 将字符串转换为字节数组。
/// </summary>
public static string ComputeHash(string input, HashMethod method = HashMethod.Md5)
=> ComputeHash(Encoding.UTF8.GetBytes(input), method);
#endregion
#region DES
private static readonly byte[] desInitialVector = Encoding.UTF8.GetBytes("95168702");
/// <summary>
/// 未指定密钥时使用的默认 DES 密钥。必须为 8 字节。
/// </summary>
public static string defaultDesKey = "@;$ Abv2";
/// <summary>
/// 使用 DES 对称加密算法加密字符串。
/// </summary>
public static string DesEncrypt(string sourceString, string? key = null) {
key = key is null ? defaultDesKey : key!.GetStableHashCode().ToString().EnsureLength('X', 8)[..8];
byte[] btKey = Encoding.UTF8.GetBytes(key);
var des = new DESCryptoServiceProvider();
using var ms = new MemoryStream();
using var cs = new CryptoStream(ms, des.CreateEncryptor(btKey, desInitialVector), CryptoStreamMode.Write);
byte[] inData = Encoding.UTF8.GetBytes(sourceString);
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// 使用 DES 对称加密算法解密字符串。
/// </summary>
public static string DesDecrypt(string encryptedString, string? key = null) {
key = key is null ? defaultDesKey : key!.GetStableHashCode().ToString().EnsureLength('X', 8)[..8];
byte[] btKey = Encoding.UTF8.GetBytes(key);
var des = new DESCryptoServiceProvider();
using var ms = new MemoryStream();
using var cs = new CryptoStream(ms, des.CreateDecryptor(btKey, desInitialVector), CryptoStreamMode.Write);
byte[] inData = Convert.FromBase64String(encryptedString);
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
return Encoding.UTF8.GetString(ms.ToArray());
}
#endregion
#region ECDSA
/// <summary>
/// 未指定公钥时的默认 ECDSA P-256 公钥。
/// </summary>
public static string defaultEcdsaPublicKey = "RUNTMSAAAAC4QTUNAewh23Q4Q6koHkyIrDIIZUSbua23sf2DiZmIRwSzadISDRyTVTbuWniH3KR7rKj8XBsabms1be6i3c+S";
/// <summary>
/// 进行 ECDSA P-256 非对称加密签名验证。
/// 如果验证失败则抛出 <see cref="CryptographicException"/>。
/// </summary>
public static void EcdsaVerify(string sourceString, string sign, string? publicKey = null) {
using var sha256 = GetHashAlgorithm(HashMethod.Sha256);
byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
IntPtr algorithmHandle = IntPtr.Zero;
IntPtr keyHandle = IntPtr.Zero;
// 直接调用 DLL,以避免 .NET API 依赖的系统服务出现问题时导致验证失败
try {
int status = BCryptOpenAlgorithmProvider(out algorithmHandle, "ECDSA_P256", null, 0);
if (status < 0) throw new CryptographicException($"{nameof(BCryptOpenAlgorithmProvider)} 失败,错误码 {status}");
status = BCryptImportKeyPair(algorithmHandle, IntPtr.Zero, "ECCPUBLICBLOB", out keyHandle, Convert.FromBase64String(publicKey ?? defaultEcdsaPublicKey), 72, 0);
if (status < 0) throw new CryptographicException($"{nameof(BCryptImportKeyPair)} 失败,错误码 {status}");
status = BCryptVerifySignature(keyHandle, IntPtr.Zero, hash, hash.Length, Convert.FromBase64String(sign), 64, 0);
if (status == unchecked((int) 0xC000A000)) throw new SecurityException("签名验证失败");
if (status < 0) throw new CryptographicException($"{nameof(BCryptVerifySignature)} 失败,错误码 {status}");
} finally {
if (keyHandle != IntPtr.Zero) BCryptDestroyKey(keyHandle);
if (algorithmHandle != IntPtr.Zero) BCryptCloseAlgorithmProvider(algorithmHandle, 0);
}
}
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptOpenAlgorithmProvider(out IntPtr algorithmHandle, string algorithmId, string? implementation, int flags);
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)] private static extern int BCryptImportKeyPair(IntPtr algorithmHandle, IntPtr importKey, string blobType, out IntPtr keyHandle, byte[] input, int inputSize, int flags);
[DllImport("bcrypt.dll")] private static extern int BCryptVerifySignature(IntPtr keyHandle, IntPtr paddingInfo, byte[] hash, int hashSize, byte[] signature, int signatureSize, int flags);
[DllImport("bcrypt.dll")] private static extern int BCryptDestroyKey(IntPtr keyHandle);
[DllImport("bcrypt.dll")] private static extern int BCryptCloseAlgorithmProvider(IntPtr algorithmHandle, int flags);
#endregion
}
+21 -8
View File
@@ -115,16 +115,28 @@ public static class DirectoryUtils {
/// <summary>
/// 删除文件夹。
/// <para/>若指定了 <paramref name="toRecycleBin"/>,则会尝试删除到回收站,但如果失败则会回退到永久删除。
/// </summary>
public static void Delete(string folder, bool toRecycleBin = false) {
if (!DirectoryUtils.Exists(folder)) return;
/// <returns>
/// 如果文件夹不存在,返回 <see langword="null"/>。
/// <para/>如果成功删除到回收站,返回 <see langword="true"/>。
/// <para/>如果永久删除,返回 <see langword="false"/>。
/// </returns>
public static bool? Delete(string folder, bool toRecycleBin = false) {
if (!DirectoryUtils.Exists(folder)) return null;
Logger.Trace($"{(toRecycleBin ? "将文件夹删除到回收站" : "删除文件夹")}:{folder}");
SafetyCheck(folder);
// 删除
// 删除到回收站
if (toRecycleBin) {
FileUtils.DeleteToRecycleBin(folder); // 删除到回收站
} else {
DeleteInternal(folder); // 永久删除
try {
FileUtils.DeleteToRecycleBin(folder);
return true;
} catch (Exception ex) {
Logger.Warn(ex, $"无法将文件夹删除到回收站,回退到永久删除:{folder}");
}
}
// 永久删除
DeleteInternal(folder);
static void DeleteInternal(string folder) {
try {
folder = PathUtils.ForApi(folder);
@@ -140,7 +152,7 @@ public static class DirectoryUtils {
}
}
}
}
return false;
}
/// <summary>
@@ -161,6 +173,7 @@ public static class DirectoryUtils {
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
Environment.GetFolderPath(Environment.SpecialFolder.Windows),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads") // 下载文件夹没有 SpecialFolder 枚举
}.Select(f => PathUtils.ForCompare(f))));
}.Where(f => f.Contains(Path.VolumeSeparatorChar)) // 当缺少某个文件夹时,GetFolderPath 会返回空字符串(#8636)
.Select(f => PathUtils.ForCompare(f))));
}
+17 -4
View File
@@ -176,16 +176,29 @@ public static class FileUtils {
/// <summary>
/// 删除文件。
/// <para/>若指定了 <paramref name="toRecycleBin"/>,则会尝试删除到回收站,但如果失败则会回退到永久删除。
/// </summary>
public static void Delete(string filePath, bool toRecycleBin = false) {
if (!FileUtils.Exists(filePath)) return;
/// <returns>
/// 如果文件不存在,返回 <see langword="null"/>。
/// <para/>如果成功删除到回收站,返回 <see langword="true"/>。
/// <para/>如果永久删除,返回 <see langword="false"/>。
/// </returns>
public static bool? Delete(string filePath, bool toRecycleBin = false) {
if (!FileUtils.Exists(filePath)) return null;
Logger.Trace($"{(toRecycleBin ? "将文件删除到回收站" : "删除文件")}:{filePath}");
// 删除到回收站
if (toRecycleBin) {
try {
DeleteToRecycleBin(filePath);
} else {
return true;
} catch (Exception ex) {
Logger.Warn(ex, $"无法将文件删除到回收站,回退到永久删除:{filePath}");
}
}
// 永久删除
ResilientUtils.RetryOn<IOException>(()
=> File.Delete(PathUtils.ForApi(filePath)));
}
return false;
}
/// <summary>
-23
View File
@@ -1,23 +0,0 @@
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))
};
Logger.Trace($"计算文件 {method}:{filePath}");
return BitConverter.ToString(hashImpl.ComputeHash(file)).Replace("-", "").ToLower();
}
}
+12 -3
View File
@@ -24,7 +24,7 @@ public static class MathUtils {
if (digit == -1 || digit >= fromRadix) throw new ArgumentException($"Character '{c}' in input '{input}' is not a valid digit for radix {fromRadix}.");
realNum = realNum * fromRadix + digit;
}
return ConvertRadix(realNum * (isNegative ? -1 : 1), toRadix);
return (realNum * (isNegative ? -1 : 1)).ConvertRadix(toRadix);
}
/// <summary>
/// 转换为 2 到 86 进制的字符串。
@@ -36,6 +36,12 @@ public static class MathUtils {
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this ulong input, int toRadix)
=> ConvertRadix((BigInteger) input, toRadix);
/// <summary>
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this int input, int toRadix)
=> ConvertRadix((BigInteger) input, toRadix);
/// <summary>
@@ -44,8 +50,11 @@ public static class MathUtils {
/// </summary>
public static string ConvertRadix(this byte input, int toRadix)
=> ConvertRadix((BigInteger) input, toRadix);
private static string ConvertRadix(this BigInteger input, int toRadix) {
/// <summary>
/// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary>
public static string ConvertRadix(this BigInteger input, int toRadix) {
const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',";
if (toRadix < 2 || toRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(toRadix), $"{nameof(toRadix)} must be between 2 and 86.");
// 零与负数的预处理
+50 -49
View File
@@ -23,31 +23,31 @@ public static class PathUtils {
/// 若路径较长,则尽量将其转换为短路径。
/// <para/>结果的开头不含 <c>\\?\</c>,结尾不含分隔符。
/// </summary>
public static string ToShortPath(string fullName, bool keepFileName = false) {
if (string.IsNullOrEmpty(fullName)) return fullName;
if (!fullName.Contains(@":\")) return fullName;
if (fullName.Length <= 200) return fullName;
fullName = PathUtils.ForCompare(fullName);
public static string ToShortPath(string pathName, bool keepFileName = false) {
if (string.IsNullOrEmpty(pathName)) return pathName;
if (!pathName.Contains(":")) return pathName;
if (pathName.Length <= 200) return pathName;
pathName = PathUtils.ForCompare(pathName);
// 保留文件名
string pathToKeep = "";
string pathToShorten = fullName;
if (fullName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
if (keepFileName && FileUtils.Exists(fullName)) {
pathToKeep = PathUtils.GetLastPart(fullName);
pathToShorten = PathUtils.RemoveLastPart(fullName);
string pathToShorten = pathName;
if (pathName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
if (keepFileName && FileUtils.Exists(pathName)) {
pathToKeep = PathUtils.GetLastPart(pathName);
pathToShorten = PathUtils.RemoveLastPart(pathName);
}
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在
string parentPath = Path.GetDirectoryName(pathToShorten);
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return fullName; // 已经到达根目录,全都不存在,直接返回
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return pathName; // 已经到达根目录,全都不存在,直接返回
pathToKeep = Path.Combine(PathUtils.GetLastPart(pathToShorten), pathToKeep);
pathToShorten = parentPath;
}
if (pathToShorten.Length <= 10) return fullName;
if (pathToShorten.Length <= 10) return pathName;
// 实际缩短路径
char[] buffer = new char[260];
int result = GetShortPathNameW(PathUtils.ForApi(pathToShorten), buffer, buffer.Length);
if (result == 0) return fullName;
if (result == 0) return pathName;
string shortPath = new(buffer, 0, result);
return PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.Combine(shortPath, pathToKeep)));
}
@@ -58,24 +58,25 @@ public static class PathUtils {
/// 将完整路径转换为以 <c>\\?\</c> 开头的扩展格式。
/// 这会去除路径末尾的分隔符,将 / 替换为 \。
/// </summary>
public static string ToExtendedFormat(string path) {
if (string.IsNullOrWhiteSpace(path)) return path;
if (path.StartsWithF(@"\\?\")) return path; // 已经是长路径
path = RemoveSlashSuffix(path).Replace('/', '\\'); // API 要求这个格式……
if (path.StartsWithF(@"\\")) {
return $@"\\?\UNC\{path.Substring(2)}";
public static string ToExtendedFormat(string pathName) {
if (string.IsNullOrWhiteSpace(pathName)) return pathName;
if (!pathName.Contains(@":")) return pathName; // 可能是相对路径,保持不变
if (pathName.StartsWithF(@"\\?\")) return pathName; // 已经是长路径
pathName = RemoveSlashSuffix(pathName).Replace('/', '\\'); // API 要求这个格式……
if (pathName.StartsWithF(@"\\")) {
return $@"\\?\UNC\{pathName[2..]}";
} else {
return $@"\\?\{path}";
return $@"\\?\{pathName}";
}
}
/// <summary>
/// 去除路径开头的 <c>\\?\</c>。
/// </summary>
public static string RemoveExtendedPrefix(string path) {
if (path.StartsWithF(@"\\?\UNC\")) return @"\\" + path.AfterLast(@"\\?\UNC\");
if (path.StartsWithF(@"\\?\")) return path.AfterLast(@"\\?\");
return path;
public static string RemoveExtendedPrefix(string pathName) {
if (pathName.StartsWithF(@"\\?\UNC\")) return @"\\" + pathName.AfterLast(@"\\?\UNC\");
if (pathName.StartsWithF(@"\\?\")) return pathName.AfterLast(@"\\?\");
return pathName;
}
#endregion
@@ -91,11 +92,11 @@ public static class PathUtils {
/// "C:\foo\" → "C:"
/// "https://foo.bar/file/pack.zip?arg=1" → "https://foo.bar/file"
/// </code></summary>
public static string RemoveLastPart(string path) {
if (path!.Contains("://")) { // 网络路径
path = PathUtils.RemoveSlashSuffix(path.BeforeFirst("#").BeforeFirst("?")); // 去除参数
public static string RemoveLastPart(string pathName) {
if (pathName!.Contains("://")) { // 网络路径
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
}
return PathUtils.RemoveSlashSuffix(path!).BeforeLastOfAny([@"\", "/"]);
return PathUtils.RemoveSlashSuffix(pathName!).BeforeLastOfAny([@"\", "/"]);
}
/// <summary>
@@ -106,13 +107,13 @@ public static class PathUtils {
/// "C:\foo\bar" → "bar"
/// "https://foo.bar/file/pack.zip?arg=1" → "pack.zip"
/// </code></summary>
public static string GetLastPart(string path) {
if (path!.Contains("://")) { // 网络路径
path = PathUtils.RemoveSlashSuffix(path.BeforeFirst("#").BeforeFirst("?")); // 去除参数
public static string GetLastPart(string pathName) {
if (pathName!.Contains("://")) { // 网络路径
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
} else { // 文件路径
path = PathUtils.RemoveSlashSuffix(path);
pathName = PathUtils.RemoveSlashSuffix(pathName);
}
return path.AfterLastOfAny([@"\", "/"]);
return pathName.AfterLastOfAny([@"\", "/"]);
}
/// <summary>
@@ -123,8 +124,8 @@ public static class PathUtils {
/// "https://foo.bar/file/page.xaml.vb?arg=1" → "page.xaml"
/// </code>
/// </summary>
public static string GetFileNameWithoutExtension(string path)
=> GetLastPart(path).BeforeLast(".");
public static string GetFileNameWithoutExtension(string pathName)
=> GetLastPart(pathName).BeforeLast(".");
/// <summary>
/// 获取路径或文件名中的最后一级文件扩展名,不包含 <c>.</c>,固定小写。
@@ -136,8 +137,8 @@ public static class PathUtils {
/// "https://foo.bar/file/page.xaml.vb?arg=1" → "vb"
/// </code>
/// </summary>
public static string GetExtension(string path) {
var name = GetLastPart(path);
public static string GetExtension(string pathName) {
var name = GetLastPart(pathName);
return name.Contains(".") ? name.AfterLast(".").Lower() : "";
}
@@ -145,29 +146,29 @@ public static class PathUtils {
/// 获取路径的盘符,返回一个大写字母。
/// 若路径不包含盘符,则返回 <c>null</c>。
/// </summary>
public static char? GetDiskName(string? path) {
if (string.IsNullOrEmpty(path)) return null;
path = PathUtils.RemoveExtendedPrefix(path!);
if (path.StartsWithF(@"\\") || path.StartsWithF("/")) return null;
return char.ToUpper(path[0]);
public static char? GetDiskName(string? pathName) {
if (string.IsNullOrEmpty(pathName)) return null;
pathName = PathUtils.RemoveExtendedPrefix(pathName!);
if (pathName.StartsWithF(@"\\") || pathName.StartsWithF("/")) return null;
return char.ToUpper(pathName[0]);
}
/// <summary>
/// 统一路径格式,以便比较。
/// <para/>具体而言:将短路径展开,去除前导的 <c>\\?\</c>,将分隔符改为 \,去除末尾的分隔符。
/// </summary>
public static string ForCompare(string path)
=> PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.GetFullPath(path)).Replace("/", @"\"));
public static string ForCompare(string pathName)
=> PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.GetFullPath(pathName)).Replace("/", @"\"));
/// <summary>
/// 将路径转换为兼容各种 Windows API 的格式。
/// <para/>具体而言:将分隔符改为 \。添加前导的 <c>\\?\</c>。若为驱动器则添加末尾分隔符,否则去除分隔符。
/// </summary>
public static string ForApi(string path) {
path = PathUtils.ToExtendedFormat(path);
if (path.EndsWithF(":")) path += @"\"; // 驱动器路径必须保留末尾的分隔符
if (path.EndsWithF(@":\")) return path;
return PathUtils.RemoveSlashSuffix(path);
public static string ForApi(string pathName) {
pathName = PathUtils.ToExtendedFormat(pathName);
if (pathName.EndsWithF(":")) pathName += @"\"; // 驱动器路径必须保留末尾的分隔符
if (pathName.EndsWithF(@":\")) return pathName;
return PathUtils.RemoveSlashSuffix(pathName);
}
#endregion
+25
View File
@@ -11,6 +11,11 @@ public static class ResilientUtils {
/// </summary>
public static void RetryOn<TException>(Action action, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "") where TException : Exception
=> RetryOn<TException, object?>(() => { action(); return null; }, maxAttempts, delayMs, caller);
/// <summary>
/// 在抛出特定异常时,延迟并自动重试。
/// </summary>
public static void RetryOn<TException1, TException2>(Action action, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "") where TException1 : Exception where TException2 : Exception
=> RetryOn<TException1, TException2, object?>(() => { action(); return null; }, maxAttempts, delayMs, caller);
/// <summary>
/// 在抛出任意异常时,延迟并自动重试。
@@ -37,5 +42,25 @@ public static class ResilientUtils {
}
}
}
/// <summary>
/// 在抛出特定异常时,延迟并自动重试。
/// </summary>
public static TOut RetryOn<TException1, TException2, TOut>(Func<TOut> func, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "") where TException1 : Exception where TException2 : Exception {
int attempt = 0;
while (true) {
try {
return func(); // 成功则退出
} catch (Exception ex) when (ex is TException1 or TException2) {
attempt++;
if (attempt < maxAttempts) {
Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,将在 {delayMs}ms 后重试");
Thread.Sleep(delayMs);
} else { // 超过最大尝试次数
Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,已到达最大尝试次数");
throw;
}
}
}
}
}