9 Commits
10 changed files with 259 additions and 70 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
}
+33 -20
View File
@@ -115,32 +115,44 @@ 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); // 永久删除
static void DeleteInternal(string folder) {
try {
folder = PathUtils.ForApi(folder);
foreach (string filePath in DirectoryUtils.GetFiles(folder, true)) FileUtils.Delete(filePath); // 删除文件
foreach (string str in DirectoryUtils.GetDirectories(folder, true)) DeleteInternal(str); // 递归删除子文件夹
ResilientUtils.RetryOn<IOException>(() => Directory.Delete(folder, true)); // 最终删除文件夹
} catch (DirectoryNotFoundException ex) { // #4549,也可能已被其他线程删除
if (DirectoryUtils.Exists(folder)) {
Logger.Warn(ex, $"该文件夹可能为孤立的符号链接,尝试直接删除({folder})");
Directory.Delete(folder);
} else {
throw;
}
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);
foreach (string filePath in DirectoryUtils.GetFiles(folder, true)) FileUtils.Delete(filePath); // 删除文件
foreach (string str in DirectoryUtils.GetDirectories(folder, true)) DeleteInternal(str); // 递归删除子文件夹
ResilientUtils.RetryOn<IOException>(() => Directory.Delete(folder, true)); // 最终删除文件夹
} catch (DirectoryNotFoundException ex) { // #4549,也可能已被其他线程删除
if (DirectoryUtils.Exists(folder)) {
Logger.Warn(ex, $"该文件夹可能为孤立的符号链接,尝试直接删除({folder})");
Directory.Delete(folder);
} else {
throw;
}
}
}
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))));
}
+19 -6
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) {
DeleteToRecycleBin(filePath);
} else {
ResilientUtils.RetryOn<IOException>(()
=> File.Delete(PathUtils.ForApi(filePath)));
try {
DeleteToRecycleBin(filePath);
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.");
// 零与负数的预处理
+1 -1
View File
@@ -63,7 +63,7 @@ public static class PathUtils {
if (path.StartsWithF(@"\\?\")) return path; // 已经是长路径
path = RemoveSlashSuffix(path).Replace('/', '\\'); // API 要求这个格式……
if (path.StartsWithF(@"\\")) {
return $@"\\?\UNC\{path.Substring(2)}";
return $@"\\?\UNC\{path[2..]}";
} else {
return $@"\\?\{path}";
}
+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;
}
}
}
}
}