Author SHA1 Message Date
龙腾猫跃 5ee6f88cde fix: 在混合使用 / 和 \ 时路径裁剪有误 2026-05-14 21:05:08 +08:00
龙腾猫跃 883b912104 Merge pull request #12 from Meloong-Git/copilot/add-overload-maxbyall-icomparert
为 MaxByAll/MinByAll/MaxBy/MinBy 添加 IComparer 重载
2026-05-14 18:04:37 +08:00
copilot-swe-agent[bot]andLTCatt 8ef8796922 feat: 为 MaxByAll/MinByAll/MaxBy/MinBy 添加 IComparer 重载
Agent-Logs-Url: https://github.com/Meloong-Git/MeloongCore/sessions/e26ccaa3-3e0f-4a45-8af2-9cfba2e43250

Co-authored-by: LTCatt <40348278+LTCatt@users.noreply.github.com>
2026-05-14 10:02:58 +00:00
龙腾猫跃 b1b18d4bb3 几个新方法 2026-05-14 17:04:53 +08:00
龙腾猫跃 159f16fd57 替换新的 Split 扩展方法 2026-05-14 12:28:02 +08:00
龙腾猫跃 14812561f9 更多 string.Split 重载 2026-05-14 12:12:40 +08:00
龙腾猫跃 454d167869 新 Split 扩展 2026-05-14 11:20:23 +08:00
龙腾猫跃 6ec4fcee5f * 2026-05-13 12:51:41 +08:00
龙腾猫跃 d3dbc23003 fix: 在长路径下,保存文件弹窗无法选择不存在的文件 2026-05-13 12:22:39 +08:00
龙腾猫跃 2b5fc810bd * 2026-05-12 23:55:23 +08:00
龙腾猫跃 f2d4070b6a fix: ToShortPath 错误地展开了相对路径 2026-05-12 21:09:55 +08:00
龙腾猫跃 f57f496d25 ref: 迁移文件 Hash 计算 2026-05-12 19:31:36 +08:00
龙腾猫跃 03483d5f7a Dialogs 2026-05-12 19:21:25 +08:00
龙腾猫跃 5edff6c73f 部分文件夹相关测试 2026-05-12 18:59:03 +08:00
龙腾猫跃 b821973e2a Merge pull request #11 from Meloong-Git/copilot/rewrite-directory-utilstest
重新编写 DirectoryUtilsTest.cs,覆盖所有分支
2026-05-12 17:52:16 +08:00
copilot-swe-agent[bot]andLTCatt 77d400a21f feat: add DirectoryUtilsTest.cs covering all Copy/Move branches and orphan symlink deletion
Agent-Logs-Url: https://github.com/Meloong-Git/MeloongCore/sessions/4480867b-7c90-4121-a021-3e642de8941e

Co-authored-by: LTCatt <40348278+LTCatt@users.noreply.github.com>
2026-05-12 09:49:18 +00:00
龙腾猫跃 f9ca4727ef * 2026-05-12 17:38:20 +08:00
龙腾猫跃 cc1bc99ab3 Merge pull request #10 from Meloong-Git/copilot/add-unit-tests-to-directory-utils
为 DirectoryUtils 编写参数化单元测试
2026-05-12 17:12:16 +08:00
龙腾猫跃 8c961fd64d * 2026-05-12 17:11:07 +08:00
copilot-swe-agent[bot]andLTCatt 518077c21e test: add DirectoryUtils unit tests with parameterized [Arguments]
Agent-Logs-Url: https://github.com/Meloong-Git/MeloongCore/sessions/59437682-6bc4-4b3e-b021-018822b60a4f

Co-authored-by: LTCatt <40348278+LTCatt@users.noreply.github.com>
2026-05-12 09:04:02 +00:00
龙腾猫跃 27e650d698 * 2026-05-12 16:59:03 +08:00
龙腾猫跃 0ff787c5d9 文件操作大小写兼容 2026-05-12 16:52:42 +08:00
龙腾猫跃 d4af33f5be fix: 驱动器根路径兼容 2026-05-12 15:12:32 +08:00
龙腾猫跃 347a51f9d4 fix: 空日志行会缺失日志前缀 2026-05-12 12:04:07 +08:00
龙腾猫跃 a10ec00951 fix: ReadAsBytes 不兼容正在使用中的文件 2026-05-12 12:01:16 +08:00
龙腾猫跃 7402647008 fix: 长路径处理有误 2026-05-12 11:54:42 +08:00
龙腾猫跃 a1a367a749 fix: 删除文件夹没有长路径处理 2026-05-09 12:53:25 +08:00
龙腾猫跃 b4c10ce79d 带缓冲区的高性能 BaseLogger 2026-05-09 12:26:54 +08:00
龙腾猫跃 5c79bb8954 ResilientUtils 代码复用 2026-05-09 11:52:03 +08:00
龙腾猫跃 b54a8f1683 Merge pull request #9 from Meloong-Git/copilot/replace-xunit-with-tunit
chore: migrate test project from xunit to TUnit
2026-05-09 09:29:47 +08:00
copilot-swe-agent[bot]andLTCatt b44fee289b chore: replace xunit with TUnit in test project
Agent-Logs-Url: https://github.com/Meloong-Git/MeloongCore/sessions/ec3e9ba1-2e5f-4e12-9954-204846b6e793

Co-authored-by: LTCatt <40348278+LTCatt@users.noreply.github.com>
2026-05-09 00:50:15 +00:00
龙腾猫跃 8c2b3b37aa 测试微调 2026-05-09 00:39:03 +08:00
龙腾猫跃 f760befa26 路径检查 2026-05-08 22:09:42 +08:00
龙腾猫跃 4f1664459d PathUtils.RemoveLastPart 2026-05-08 21:27:04 +08:00
龙腾猫跃 256db1e973 ResilientUtils 2026-05-08 19:47:21 +08:00
龙腾猫跃 86544de606 DirectoryUtils.Delete 2026-05-08 15:35:18 +08:00
龙腾猫跃 e4a70e2447 TryReadAsString、TryReadAsLines 2026-05-07 21:39:38 +08:00
龙腾猫跃 fbc25509bc ReadAsLines、SplitLines 2026-05-07 21:08:57 +08:00
龙腾猫跃 29f2ee58ac ReadAsString、ReadAsLines 2026-05-07 20:54:49 +08:00
龙腾猫跃 db15780671 ref: Stream.ReadString,byte[].GetString 2026-05-07 20:43:34 +08:00
龙腾猫跃 c2d052e1ca ReadAsBytes 2026-05-07 19:37:42 +08:00
龙腾猫跃 0e8671a7af ref: 一些路径处理 2026-05-07 18:28:17 +08:00
龙腾猫跃 ffb79cf1eb ref: Log 内插优化 2026-05-07 16:05:03 +08:00
龙腾猫跃 487f54e4a9 Merge pull request #8 from Meloong-Git/copilot/optimize-logging-with-interpolated-string-handler
为日志实现 InterpolatedStringHandler 优化,替代 lambda 懒获取
2026-05-07 12:30:07 +08:00
copilot-swe-agent[bot]andLTCatt 4e07bcf17a feat: implement InterpolatedStringHandler for Logger, replace Func<string> lambda overloads
Agent-Logs-Url: https://github.com/Meloong-Git/MeloongCore/sessions/186510eb-a481-4e72-b83d-a3e77c103fc6

Co-authored-by: LTCatt <40348278+LTCatt@users.noreply.github.com>
2026-05-07 04:21:38 +00:00
龙腾猫跃 e391dd22b6 ref: DirectoryUtils.Copy 2026-05-07 11:57:08 +08:00
龙腾猫跃 9a77157dcf ref: 迁移 ValueConverter 2026-05-07 11:26:31 +08:00
龙腾猫跃 2d682afd2c 正则 2026-05-07 11:07:19 +08:00
龙腾猫跃 b26e2c77e6 ref: PathUtils.RemoveFileName 2026-05-07 10:23:17 +08:00
龙腾猫跃 6bce8a6515 * 2026-05-07 09:55:36 +08:00
龙腾猫跃 368280fcb5 Code Review 2 2026-05-07 09:20:23 +08:00
龙腾猫跃 9158a69b62 Code Review 2026-05-07 08:46:48 +08:00
龙腾猫跃 be6336f548 Merge pull request #7 from Meloong-Git/copilot/refactor-exception-extensions
refactor: support AggregateException in GetDisplay and IsBadNetwork via Flatten
2026-05-07 08:03:11 +08:00
copilot-swe-agent[bot]andLTCatt 983ae1af11 refactor: use Flatten in GetDisplay and IsBadNetwork to support AggregateException
Agent-Logs-Url: https://github.com/Meloong-Git/MeloongCore/sessions/e67129f9-62f2-41e0-82d3-019771a8e525

Co-authored-by: LTCatt <40348278+LTCatt@users.noreply.github.com>
2026-05-06 23:40:54 +00:00
龙腾猫跃 49c2a9c8ff format 2026-05-07 07:33:06 +08:00
龙腾猫跃 c017654b6a misc 2026-05-07 07:11:26 +08:00
26 changed files with 1707 additions and 511 deletions

No files matched your search

+152 -37
View File
@@ -1,24 +1,27 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Globalization;
namespace MeloongCore.Extensions; namespace MeloongCore.Extensions;
public static class EnumerableExtensions { public static class EnumerableExtensions {
#region Distinct #region 去重
/// <summary> /// <summary>
/// 通过比较器进行去重。 /// 通过比较器进行去重。
/// 该方法的效率较低,建议仅在小型列表上使用,或换用 DistinctBy。 /// 该方法的效率较低,建议仅在小型列表上使用,或换用 DistinctBy。
/// </summary> /// </summary>
public static IEnumerable<T> Distinct<T>(this IList<T> list, Func<T, T, bool> comparer) { public static IEnumerable<T> Distinct<T>(this IList<T> list, Func<T, T, bool> comparer) {
for (int i = 0; i < list.Count; i++) { var seen = new List<T>();
if (!list.Skip(i + 1).Any(item => comparer(list[i], item))) yield return list[i]; foreach (var item in list) {
if (!seen.Any(s => comparer(s, item))) {
seen.Add(item);
yield return item;
}
} }
} }
/// <summary> /// <summary>
/// 按对象的指定值去重。 /// 按对象的指定值去重。
/// </summary> /// </summary>
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector) { public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) {
var seen = new HashSet<TKey>(); var seen = new HashSet<TKey>();
foreach (var element in source) { foreach (var element in source) {
if (seen.Add(selector(element))) yield return element; if (seen.Add(selector(element))) yield return element;
@@ -27,29 +30,29 @@ public static class EnumerableExtensions {
/// <summary> /// <summary>
/// 按对象的指定值去重。 /// 按对象的指定值去重。
/// </summary> /// </summary>
public static ParallelQuery<T> DistinctBy<T, TKey>(this ParallelQuery<T> source, Func<T, TKey> selector) { public static ParallelQuery<TSource> DistinctBy<TSource, TKey>(this ParallelQuery<TSource> source, Func<TSource, TKey> selector) {
var seen = new ConcurrentDictionary<TKey, bool>(); var seen = new ConcurrentDictionary<TKey, bool>();
return source.Where(element => seen.TryAdd(selector(element), true)); return source.Where(element => seen.TryAdd(selector(element), true));
} }
#endregion #endregion
#region MinBy / MaxBy #region 最大 / 最小
/// <summary> /// <summary>
/// 选择所有最大值对应的对象。 /// 选择所有最大值对应的对象。
/// 若没有元素则返回空列表。 /// 若没有元素则返回空列表。
/// </summary> /// </summary>
public static List<TKey> MaxByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> { public static List<TSource> MaxByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
var results = new List<TKey>(); var results = new List<TSource>();
using var enumerator = source.GetEnumerator(); using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return results; if (!enumerator.MoveNext()) return results;
TKey maxItem = enumerator.Current; TSource maxItem = enumerator.Current;
TValue maxValue = selector(maxItem); TKey maxValue = selector(maxItem);
results.Add(maxItem); results.Add(maxItem);
while (enumerator.MoveNext()) { while (enumerator.MoveNext()) {
TKey currentItem = enumerator.Current; TSource currentItem = enumerator.Current;
TValue currentValue = selector(currentItem); TKey currentValue = selector(currentItem);
int comparisonResult = currentValue.CompareTo(maxValue); int comparisonResult = currentValue.CompareTo(maxValue);
if (comparisonResult > 0) { if (comparisonResult > 0) {
maxValue = currentValue; maxValue = currentValue;
@@ -62,19 +65,44 @@ public static class EnumerableExtensions {
return results; return results;
} }
/// <summary> /// <summary>
/// 选择所有最大值对应的对象。
/// 若没有元素则返回空列表。
/// </summary>
public static List<TSource> MaxByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) {
var results = new List<TSource>();
using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return results;
TSource maxItem = enumerator.Current;
TKey maxValue = selector(maxItem);
results.Add(maxItem);
while (enumerator.MoveNext()) {
TSource currentItem = enumerator.Current;
TKey currentValue = selector(currentItem);
int comparisonResult = comparer.Compare(currentValue, maxValue);
if (comparisonResult > 0) {
maxValue = currentValue;
results.Clear();
results.Add(currentItem);
} else if (comparisonResult == 0) {
results.Add(currentItem);
}
}
return results;
}
/// <summary>
/// 选择所有最小值对应的对象。 /// 选择所有最小值对应的对象。
/// 若没有元素则返回空列表。 /// 若没有元素则返回空列表。
/// </summary> /// </summary>
public static List<TKey> MinByAll<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> { public static List<TSource> MinByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
var results = new List<TKey>(); var results = new List<TSource>();
using var enumerator = source.GetEnumerator(); using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return results; if (!enumerator.MoveNext()) return results;
TKey minItem = enumerator.Current; TSource minItem = enumerator.Current;
TValue minValue = selector(minItem); TKey minValue = selector(minItem);
results.Add(minItem); results.Add(minItem);
while (enumerator.MoveNext()) { while (enumerator.MoveNext()) {
TKey currentItem = enumerator.Current; TSource currentItem = enumerator.Current;
TValue currentValue = selector(currentItem); TKey currentValue = selector(currentItem);
int comparisonResult = currentValue.CompareTo(minValue); int comparisonResult = currentValue.CompareTo(minValue);
if (comparisonResult < 0) { if (comparisonResult < 0) {
minValue = currentValue; minValue = currentValue;
@@ -86,18 +114,43 @@ public static class EnumerableExtensions {
} }
return results; return results;
} }
/// <summary>
/// 选择所有最小值对应的对象。
/// 若没有元素则返回空列表。
/// </summary>
public static List<TSource> MinByAll<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) {
var results = new List<TSource>();
using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return results;
TSource minItem = enumerator.Current;
TKey minValue = selector(minItem);
results.Add(minItem);
while (enumerator.MoveNext()) {
TSource currentItem = enumerator.Current;
TKey currentValue = selector(currentItem);
int comparisonResult = comparer.Compare(currentValue, minValue);
if (comparisonResult < 0) {
minValue = currentValue;
results.Clear();
results.Add(currentItem);
} else if (comparisonResult == 0) {
results.Add(currentItem);
}
}
return results;
}
/// <summary> /// <summary>
/// 选择最大值对应的对象。 /// 选择最大值对应的对象。
/// 若没有元素则返回 null。 /// 若没有元素则返回 null。
/// </summary> /// </summary>
public static TKey? MaxBy<TKey, TValue>(this IEnumerable<TKey> source, Func<TKey, TValue> selector) where TValue : IComparable<TValue> { public static TSource? MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
using var enumerator = source.GetEnumerator(); using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return default; if (!enumerator.MoveNext()) return default;
TKey maxItem = enumerator.Current; TSource maxItem = enumerator.Current;
TValue maxValue = selector(maxItem); TKey maxValue = selector(maxItem);
while (enumerator.MoveNext()) { while (enumerator.MoveNext()) {
TValue value = selector(enumerator.Current); TKey value = selector(enumerator.Current);
if (value.CompareTo(maxValue) <= 0) continue; if (value.CompareTo(maxValue) <= 0) continue;
maxItem = enumerator.Current; maxItem = enumerator.Current;
maxValue = value; maxValue = value;
@@ -105,22 +158,72 @@ public static class EnumerableExtensions {
return maxItem; return maxItem;
} }
/// <summary> /// <summary>
/// 选择最大值对应的对象。
/// 若没有元素则返回 null。
/// </summary>
public static TSource? MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) {
using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return default;
TSource maxItem = enumerator.Current;
TKey maxValue = selector(maxItem);
while (enumerator.MoveNext()) {
TKey value = selector(enumerator.Current);
if (comparer.Compare(value, maxValue) <= 0) continue;
maxItem = enumerator.Current;
maxValue = value;
}
return maxItem;
}
/// <summary>
/// 选择最小值对应的对象。 /// 选择最小值对应的对象。
/// 若没有元素则返回 null。 /// 若没有元素则返回 null。
/// </summary> /// </summary>
public static TKey? MinBy<TKey, TValue>(this IEnumerable<TKey> List, Func<TKey, TValue> Selector) where TValue : IComparable<TValue> { public static TSource? MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) where TKey : IComparable<TKey> {
using var enumerator = List.GetEnumerator(); using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) { return default; } if (!enumerator.MoveNext()) { return default; }
TKey minItem = enumerator.Current; TSource minItem = enumerator.Current;
TValue minValue = Selector(minItem); TKey minValue = selector(minItem);
while (enumerator.MoveNext()) { while (enumerator.MoveNext()) {
TValue value = Selector(enumerator.Current); TKey value = selector(enumerator.Current);
if (value.CompareTo(minValue) >= 0) { continue; } if (value.CompareTo(minValue) >= 0) { continue; }
minItem = enumerator.Current; minItem = enumerator.Current;
minValue = value; minValue = value;
} }
return minItem; return minItem;
} }
/// <summary>
/// 选择最小值对应的对象。
/// 若没有元素则返回 null。
/// </summary>
public static TSource? MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer) {
using var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) { return default; }
TSource minItem = enumerator.Current;
TKey minValue = selector(minItem);
while (enumerator.MoveNext()) {
TKey value = selector(enumerator.Current);
if (comparer.Compare(value, minValue) >= 0) { continue; }
minItem = enumerator.Current;
minValue = value;
}
return minItem;
}
#endregion
#region 排序
/// <summary>
/// 使用默认比较器对集合进行排序。顺序为从小到大。
/// </summary>
public static IEnumerable<T> Ordered<T>(this IEnumerable<T> source) where T : IComparable<T>
=> source.OrderBy(x => x);
/// <summary>
/// 使用默认比较器对集合进行排序。顺序为从大到小。
/// </summary>
public static IEnumerable<T> OrderedDescending<T>(this IEnumerable<T> source) where T : IComparable<T>
=> source.OrderByDescending(x => x);
#endregion #endregion
@@ -166,7 +269,8 @@ public static class EnumerableExtensions {
/// 从 <see cref="ConcurrentDictionary{TKey, TValue}"/> 中移除具有指定键的元素。 /// 从 <see cref="ConcurrentDictionary{TKey, TValue}"/> 中移除具有指定键的元素。
/// 返回是否确实移除了元素。 /// 返回是否确实移除了元素。
/// </summary> /// </summary>
public static bool Remove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key) => dict.TryRemove(key, out _); public static bool Remove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key)
=> dict.TryRemove(key, out _);
/// <summary> /// <summary>
/// 将二维数组转换为字典。 /// 将二维数组转换为字典。
@@ -182,8 +286,8 @@ public static class EnumerableExtensions {
/// <summary> /// <summary>
/// 尝试从字典中获取某项,如果该项不存在,则返回默认值。 /// 尝试从字典中获取某项,如果该项不存在,则返回默认值。
/// </summary> /// </summary>
public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue = default!) => public static TValue? GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue? defaultValue = default)
dict.TryGetValue(key, out var result) ? result : defaultValue; => dict.TryGetValue(key, out var result) ? result : defaultValue;
/// <summary> /// <summary>
/// 将值添加到字典的对应项的列表中。 /// 将值添加到字典的对应项的列表中。
@@ -205,19 +309,30 @@ public static class EnumerableExtensions {
/// <remarks> /// <remarks>
/// 会跳过:0、非 2 的幂的值、不在枚举值中的数、组合值、对应同一个枚举项的多个别名。 /// 会跳过:0、非 2 的幂的值、不在枚举值中的数、组合值、对应同一个枚举项的多个别名。
/// </remarks> /// </remarks>
public static IEnumerable<T> Flags<T>(this T value) where T : struct, Enum { public static IEnumerable<T> Flags<T>(this T value) where T : struct, Enum
foreach (var element in Enum.GetValues(typeof(T)).Cast<T>().Distinct()) { => EnumUtils.GetAllFlags<T>().Where(element => value.HasFlag(element));
var number = Convert.ToInt64(element, CultureInfo.InvariantCulture);
if (number == 0 || (number & (number - 1)) != 0) continue; // 跳过 0 和非 2 的幂的值 /// <summary>
if (value.HasFlag(element)) yield return element; /// 从集合中移除满足条件的元素。
/// </summary>
public static void RemoveIf<T>(this ICollection<T> source, Func<T, bool> predicate) {
var itemsToRemove = source.Where(predicate).ToList();
foreach (var item in itemsToRemove) source.Remove(item);
} }
/// <summary>
/// 仅保留满足条件的元素,移除不满足条件的元素。
/// </summary>
public static void KeepIf<T>(this ICollection<T> source, Func<T, bool> predicate) {
var itemsToRemove = source.Where(item => !predicate(item)).ToList();
foreach (var item in itemsToRemove) source.Remove(item);
} }
/// <summary> /// <summary>
/// 判断集合是否有且仅有一个元素。 /// 判断集合是否有且仅有一个元素。
/// 在输入 null 时返回 false。 /// 在输入 null 时返回 false。
/// </summary> /// </summary>
public static bool IsSingle<T>([AllowNull] this IEnumerable<T> source) { public static bool IsSingle<T>(this IEnumerable<T>? source) {
if (source is null) return false; if (source is null) return false;
if (source is IList<T> list) return list.Count == 1; if (source is IList<T> list) return list.Count == 1;
using var enumerator = source.GetEnumerator(); using var enumerator = source.GetEnumerator();
+27 -7
View File
@@ -11,6 +11,24 @@ public static class ExceptionExtensions {
return ex; return ex;
} }
/// <summary>
/// 将异常所有的 <see cref="Exception.InnerException"/> 展开。
/// 若为 <see cref="AggregateException"/>,也会展开其中所有的子异常。
/// </summary>
public static IEnumerable<Exception> Flatten(this Exception ex) {
var toFlatten = new Stack<Exception>();
toFlatten.Push(ex);
while (toFlatten.Any()) {
var current = toFlatten.Pop();
yield return current;
if (current is AggregateException ag) {
foreach (var inner in ag.InnerExceptions) toFlatten.Push(inner);
} else if (current.InnerException is not null) {
toFlatten.Push(current.InnerException);
}
}
}
/// <summary> /// <summary>
/// 获取 <paramref name="ex"/> 的用户友好描述。 /// 获取 <paramref name="ex"/> 的用户友好描述。
/// 若 <paramref name="showMultilineStacks"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。 /// 若 <paramref name="showMultilineStacks"/> 为 true,则返回多行的详细描述与堆栈信息;否则不整理堆栈,仅将 <see cref="Exception.Message"/> 汇总到一行。
@@ -21,14 +39,14 @@ public static class ExceptionExtensions {
// 提取堆栈信息 // 提取堆栈信息
var lines = new List<string>(); var lines = new List<string>();
bool isInnerException = false; bool isInnerException = false;
for (Exception? currentEx = ex; currentEx is not null; currentEx = currentEx.InnerException) { foreach (var currentEx in ex.Flatten()) {
if (showMultilineStacks) { if (showMultilineStacks) {
lines.Add((isInnerException ? "→ " : "") + currentEx.Message.ReplaceLineEndings("\r\n", true)); lines.Add((isInnerException ? "→ " : "") + currentEx.Message.ReplaceLineEndings("\r\n", true));
if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName); var stackLines = (currentEx.StackTrace?.SplitLines(true) ?? [])
var stackLines = (currentEx.StackTrace?.ReplaceLineEndings("\r", true).Split('\r') ?? []) .Select(l => l.BeforeLast("(") + l.AfterLast(")"))
.Select(l => l.BeforeFirst("(") + l.AfterFirst(")"))
.Distinct(); .Distinct();
lines.AddRange(stackLines); lines.AddRange(stackLines);
if (currentEx.GetType() != typeof(Exception)) lines.Add(" 错误类型:" + currentEx.GetType().FullName);
} else { } else {
lines.Add(currentEx.Message.ReplaceLineEndings(" ", true)); lines.Add(currentEx.Message.ReplaceLineEndings(" ", true));
} }
@@ -62,7 +80,7 @@ public static class ExceptionExtensions {
lines.Reverse(); lines.Reverse();
return lines.Join(" ← "); return lines.Join(" ← ");
} else { } else {
return commonReason + "详细错误:" + lines.First(); return $"{commonReason}({lines.First()})";
} }
} }
} }
@@ -71,9 +89,11 @@ public static class ExceptionExtensions {
/// 判断该异常是否是由于网络连接不良导致。 /// 判断该异常是否是由于网络连接不良导致。
/// </summary> /// </summary>
public static bool IsBadNetwork(this Exception ex) { public static bool IsBadNetwork(this Exception ex) {
for (Exception? currentEx = ex; currentEx is not null; currentEx = currentEx.InnerException) { foreach (var currentEx in ex.Flatten()) {
if (currentEx is TimeoutException) { if (currentEx is TimeoutException) {
return true; return true;
} else if (currentEx is TaskCanceledException) {
return true;
} else if (currentEx is HttpRequestCodeException reqEx) { } else if (currentEx is HttpRequestCodeException reqEx) {
if (reqEx.StatusCode is HttpStatusCode.Forbidden) return false; if (reqEx.StatusCode is HttpStatusCode.Forbidden) return false;
if (reqEx.StatusCode is HttpStatusCode.RequestTimeout) return true; if (reqEx.StatusCode is HttpStatusCode.RequestTimeout) return true;
@@ -87,7 +107,7 @@ public static class ExceptionExtensions {
WebExceptionStatus.ProxyNameResolutionFailure) return true; WebExceptionStatus.ProxyNameResolutionFailure) return true;
} else if (currentEx is SocketException socketEx) { } else if (currentEx is SocketException socketEx) {
if (socketEx.SocketErrorCode is SocketError.NetworkDown or SocketError.NetworkUnreachable or SocketError.NetworkReset or SocketError.ConnectionAborted or 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.HostDown or SocketError.HostUnreachable or SocketError.ConnectionReset or SocketError.TimedOut or SocketError.ConnectionRefused or SocketError.HostUnreachable or
SocketError.HostNotFound or SocketError.TryAgain or SocketError.NoData) return true; SocketError.HostNotFound or SocketError.TryAgain or SocketError.NoData) return true;
} }
} }
+272 -94
View File
@@ -1,4 +1,5 @@
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using static System.Net.Mime.MediaTypeNames;
namespace MeloongCore.Extensions; namespace MeloongCore.Extensions;
public static class StringExtensions { public static class StringExtensions {
@@ -6,146 +7,227 @@ public static class StringExtensions {
#region 区域性 / 大小写 简化 #region 区域性 / 大小写 简化
/// <summary> /// <summary>
/// 高速的 StartsWith。 /// 非区域性的 <see cref="string.StartsWith(string)"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool StartsWithF(this string? value, string prefix, bool ignoreCase = false) { public static bool StartsWithF(this string? value, string prefix, bool ignoreCase = false)
if (value is null) return false; => value?.StartsWith(prefix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
return value.StartsWith(prefix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// 高速的 StartsWith。 /// 判断字符串是否以 <paramref name="prefix"/> 开头。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool StartsWithF(this string? value, char prefix, bool ignoreCase = false) { public static bool StartsWithF(this string? value, char prefix, bool ignoreCase = false)
if (value is null) return false; => value?.StartsWith(prefix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
return value.StartsWith(prefix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// 高速的 EndsWith。 /// 非区域性的 <see cref="string.EndsWith(string)"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool EndsWithF(this string? value, string suffix, bool ignoreCase = false) { public static bool EndsWithF(this string? value, string suffix, bool ignoreCase = false)
if (value is null) return false; => value?.EndsWith(suffix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
return value.EndsWith(suffix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// 高速的 EndsWith。 /// 判断字符串是否以 <paramref name="suffix"/> 结尾。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool EndsWithF(this string? value, char suffix, bool ignoreCase = false) { public static bool EndsWithF(this string? value, char suffix, bool ignoreCase = false)
if (value is null) return false; => value?.EndsWith(suffix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) ?? false;
return value.EndsWith(suffix.ToString(), ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// 忽略大小写的 Contains。 /// 忽略大小写的 <see cref="string.Contains(string)"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool ContainsIgnoreCase(this string value, string subString) { public static bool ContainsIgnoreCase(this string value, string subString)
return value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0; => value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
}
/// <summary> /// <summary>
/// 高速的 IndexOf。 /// 非区域性的 <see cref="string.IndexOf(string)"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOfF(this string value, string subString, bool ignoreCase = false) { public static int IndexOfF(this string value, string subString, bool ignoreCase = false)
return value.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); => value.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// 高速的 IndexOf。 /// 非区域性的 <see cref="string.IndexOf(string, int)"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int IndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false) { public static int IndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false)
return value.IndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); => value.IndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// 高速的 LastIndexOf。 /// 非区域性的 <see cref="string.LastIndexOf(string)"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int LastIndexOfF(this string value, string subString, bool ignoreCase = false) { public static int LastIndexOfF(this string value, string subString, bool ignoreCase = false)
return value.LastIndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); => value.LastIndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// 高速的 LastIndexOf。 /// 非区域性的 <see cref="string.LastIndexOf(string, int)"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int LastIndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false) { public static int LastIndexOfF(this string value, string subString, int startIndex, bool ignoreCase = false)
return value.LastIndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); => value.LastIndexOf(subString, startIndex, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary> /// <summary>
/// ToLowerInvariant 的简略写法。 /// <see cref="string.ToLowerInvariant"/> 的简略写法。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string Lower(this string str) => str.ToLowerInvariant(); public static string Lower(this string str)
=> str.ToLowerInvariant();
/// <summary> /// <summary>
/// ToUpperInvariant 的简略写法。 /// <see cref="string.ToUpperInvariant"/> 的简略写法。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string Upper(this string str) => str.ToUpperInvariant(); public static string Upper(this string str)
=> str.ToUpperInvariant();
#endregion #endregion
#region 分割与裁切 #region Split
/// <summary> /// <summary>
/// 分割字符串。 /// 分割字符串。
/// 若原始字符串为空,则返回 {""}。 /// 若原始字符串为空,则返回 {""}。
/// </summary> /// </summary>
public static string[] Split(this string fullStr, string splitStr) { public static string[] Split(this string fullStr, string splitStr, bool removeEmptyEntries = false) {
if (splitStr.IsSingle()) if (splitStr.IsSingle()) {
return fullStr.Split(splitStr[0]); return fullStr.Split(splitStr[0], removeEmptyEntries);
else } else {
return fullStr.Split([splitStr], StringSplitOptions.None); return fullStr.Split([splitStr], removeEmptyEntries);
}
}
/// <summary>
/// 分割字符串。
/// 若原始字符串为空,则返回 {""}。
/// </summary>
public static string[] Split(this string fullStr, char splitChar, bool removeEmptyEntries = false)
=> fullStr.Split([splitChar], removeEmptyEntries);
/// <summary>
/// 分割字符串。
/// 若原始字符串为空,则返回 {""}。
/// </summary>
public static string[] Split(this string fullStr, string[] splitStrings, bool removeEmptyEntries = false)
=> fullStr.Split(splitStrings, removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
/// <summary>
/// 分割字符串。
/// 若原始字符串为空,则返回 {""}。
/// </summary>
public static string[] Split(this string fullStr, char[] splitChars, bool removeEmptyEntries = false)
=> fullStr.Split(splitChars, removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
/// <summary>
/// 将字符串分割为多行。
/// </summary>
public static string[] SplitLines(this string input, bool skipEmptyLines = false)
=> input.ReplaceLineEndings("\n").Split('\n', skipEmptyLines);
#endregion
#region 裁切
/// <summary>
/// 获取在子字符串第一次出现之前的部分,如果未找到子字符串则不裁切。
/// <code>"2024/11/08".BeforeFirst("/") => "2024"</code>
/// </summary>
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);
}
/// <summary>
/// 获取在任意子字符串第一次出现之前的部分,如果未找到任意子字符串则不裁切。
/// <code>"2024/11-08".BeforeFirstOfAny(["/", "-"]) => "2024"</code>
/// </summary>
public static string BeforeFirstOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
if (texts == null) return str;
int pos = -1;
foreach (string text in texts) {
if (string.IsNullOrEmpty(text)) continue;
int p = str.IndexOfF(text, ignoreCase);
if (p >= 0 && (pos < 0 || pos > p)) pos = p;
}
if (pos < 0) return str;
return str.Substring(0, pos);
} }
/// <summary> /// <summary>
/// 获取在子字符串第一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024。 /// 获取在子字符串最后一次出现之前的部分,如果未找到子字符串则不裁切。
/// 如果未找到子字符串则不裁切。 /// <code>"2024/11/08".BeforeLast("/") => "2024/11"</code>
/// </summary> /// </summary>
public static string BeforeFirst(this string str, [AllowNull] string text, bool ignoreCase = false) { public static string BeforeLast(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.LastIndexOfF(text, ignoreCase);
if (pos >= 0) if (pos < 0) return str;
return str.Substring(0, pos); return str.Substring(0, pos);
else
return str;
} }
/// <summary> /// <summary>
/// 获取在子字符串最后一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024/11。 /// 获取在任意子字符串最后一次出现之前的部分,如果未找到任意子字符串则不裁切。
/// 如果未找到子字符串则不裁切。 /// <code>"2024/11-08".BeforeLastOfAny(["/", "-"]) => "2024/11"</code>
/// </summary> /// </summary>
public static string BeforeLast(this string str, [AllowNull] string text, bool ignoreCase = false) { public static string BeforeLastOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase); if (texts == null) return str;
if (pos >= 0) int pos = -1;
foreach (string text in texts) {
if (string.IsNullOrEmpty(text)) continue;
int p = str.LastIndexOfF(text, ignoreCase);
if (p >= 0 && (pos < 0 || pos < p)) pos = p;
}
if (pos < 0) return str;
return str.Substring(0, pos); return str.Substring(0, pos);
else
return str;
} }
/// <summary> /// <summary>
/// 获取在子字符串第一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 11/08。 /// 获取在子字符串第一次出现之后的部分,如果未找到子字符串则不裁切。
/// 如果未找到子字符串则不裁切。 /// <code>"2024/11/08".AfterFirst("/") => "11/08"</code>
/// </summary> /// </summary>
public static string AfterFirst(this string str, [AllowNull] string text, bool ignoreCase = false) { 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) if (pos < 0) return str;
return str.Substring(pos + text!.Length); return str.Substring(pos + text!.Length);
else
return str;
} }
/// <summary> /// <summary>
/// 获取在子字符串最后一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 08。 /// 获取在任意子字符串第一次出现之后的部分,如果未找到任意子字符串则不裁切。
/// 如果未找到子字符串则不裁切。 /// <code>"2024/11-08".AfterFirstOfAny(["/", "-"]) => "11-08"</code>
/// </summary> /// </summary>
public static string AfterLast(this string str, [AllowNull] string text, bool ignoreCase = false) { public static string AfterFirstOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
int pos = string.IsNullOrEmpty(text) ? -1 : str.LastIndexOfF(text!, ignoreCase); if (texts == null) return str;
if (pos >= 0) int pos = -1;
int len = 0;
foreach (string text in texts) {
if (string.IsNullOrEmpty(text)) continue;
int p = str.IndexOfF(text, ignoreCase);
if (p >= 0 && (pos < 0 || pos > p)) {
pos = p;
len = text.Length;
}
}
if (pos < 0) return str;
return str.Substring(pos + len);
}
/// <summary>
/// 获取在子字符串最后一次出现之后的部分,如果未找到子字符串则不裁切。
/// <code>"2024/11/08".AfterLast("/") => "08"</code>
/// </summary>
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.Substring(pos + text!.Length);
else }
return str; /// <summary>
/// 获取在任意子字符串最后一次出现之后的部分,如果未找到任意子字符串则不裁切。
/// <code>"2024/11-08".AfterLastOfAny(["/", "-"]) => "08"</code>
/// </summary>
public static string AfterLastOfAny(this string str, IEnumerable<string> texts, bool ignoreCase = false) {
if (texts == null) return str;
int pos = -1;
int len = 0;
foreach (string text in texts) {
if (string.IsNullOrEmpty(text)) continue;
int p = str.LastIndexOfF(text, ignoreCase);
if (p >= 0 && (pos < 0 || pos < p)) {
pos = p;
len = text.Length;
}
}
if (pos < 0) return str;
return str.Substring(pos + len);
} }
/// <summary> /// <summary>
@@ -155,19 +237,21 @@ public static class StringExtensions {
/// </summary> /// </summary>
public static string Between(this string str, string after, string before, bool ignoreCase = false) { public static string Between(this string str, string after, string before, bool ignoreCase = false) {
int startPos = string.IsNullOrEmpty(after) ? -1 : str.LastIndexOfF(after, ignoreCase); int startPos = string.IsNullOrEmpty(after) ? -1 : str.LastIndexOfF(after, ignoreCase);
if (startPos >= 0) if (startPos >= 0) {
startPos += after.Length; startPos += after.Length;
else } else {
startPos = 0; startPos = 0;
}
int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase); int endPos = string.IsNullOrEmpty(before) ? -1 : str.IndexOfF(before, startPos, ignoreCase);
if (endPos >= 0) if (endPos >= 0) {
return str.Substring(startPos, endPos - startPos); return str.Substring(startPos, endPos - startPos);
else if (startPos > 0) } else if (startPos > 0) {
return str.Substring(startPos); return str.Substring(startPos);
else } else {
return str; return str;
} }
}
#endregion #endregion
@@ -175,20 +259,113 @@ public static class StringExtensions {
/// <summary> /// <summary>
/// 替换字符串中的内容。 /// 替换字符串中的内容。
/// 仅当需要替换时,才调用 <paramref name="newValue"/> 获取结果字符串。 /// 仅当需要替换时,才调用 <paramref name="newValueGetter"/> 获取结果字符串。
/// </summary> /// </summary>
public static string ReplaceOnDemand(this string str, string oldValue, Func<string> newValue) => public static string Replace(this string str, string oldValue, Func<string> newValueGetter)
str.Contains(oldValue) ? str.Replace(oldValue, newValue()) : str; => str.Contains(oldValue) ? str.Replace(oldValue, newValueGetter()) : str;
/// <summary> /// <summary>
/// 将字符串中的换行符统一替换为指定字符。 /// 将字符串中的换行符统一替换为指定字符串。
/// 若指定了 <paramref name="mergeMultiple"/>,会将多个连续换行符仅替换为一个目标内容。 /// 若指定了 <paramref name="mergeMultiple"/>,会将多个连续换行符仅替换为一个目标内容。
/// </summary> /// </summary>
public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false) => public static string ReplaceLineEndings(this string input, string newValue, bool mergeMultiple = false)
Regex.Replace(input, => (mergeMultiple ? regexLineEndingAndMerge : regexLineEnding).Replace(input, newValue.Replace("$", "$$")); // 避免识别成捕获组
mergeMultiple ? @"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+" : @"\r\n|[\n\r\f\u0085\u2028\u2029]", private static readonly Regex regexLineEndingAndMerge = new(@"(?:\r\n|[\n\r\f\u0085\u2028\u2029])+", RegexOptions.Compiled);
newValue.Replace("$", "$$"), // 避免识别成捕获组 private static readonly Regex regexLineEnding = new(@"\r\n|[\n\r\f\u0085\u2028\u2029]", RegexOptions.Compiled);
RegexOptions.Compiled);
#endregion
#region 正则
/// <summary>
/// 搜索字符串中所有的正则匹配项。
/// </summary>
public static IEnumerable<string> RegexSearch(this string str, string pattern, RegexOptions options = RegexOptions.None) {
try {
return Regex.Matches(str, pattern, options).Cast<Match>().Select(m => m.Value);
} catch (Exception ex) {
Logger.Warn(ex, $"{nameof(RegexSearch)} 失败({pattern})");
return [];
}
}
/// <summary>
/// 获取字符串中的第一个正则匹配项,若无匹配或失败则返回 <see langword="null"/>。
/// </summary>
public static string? RegexSeek(this string str, string pattern, RegexOptions options = RegexOptions.None) {
try {
var match = Regex.Match(str, pattern, options);
return match.Success ? match.Value : null;
} catch (Exception ex) {
Logger.Warn(ex, $"{nameof(RegexSeek)} 失败({pattern})");
return null;
}
}
/// <summary>
/// 检查字符串是否匹配某正则模式。
/// </summary>
public static bool RegexCheck(this string str, string pattern, RegexOptions options = RegexOptions.None) {
try {
return Regex.IsMatch(str, pattern, options);
} catch (Exception ex) {
Logger.Warn(ex, $"{nameof(RegexCheck)} 失败({pattern})");
return false;
}
}
/// <summary>
/// 进行正则替换。
/// 失败时会抛出异常。
/// </summary>
public static string RegexReplace(this string allContents, string searchRegex, string replaceTo, RegexOptions options = RegexOptions.None) {
return Regex.Replace(allContents, searchRegex, replaceTo, options);
}
/// <summary>
/// 对每个正则匹配分别进行替换。
/// 失败时会抛出异常。
/// </summary>
public static string RegexReplace(this string allContents, string searchRegex, MatchEvaluator replaceTo, RegexOptions options = RegexOptions.None) {
return Regex.Replace(allContents, searchRegex, replaceTo, options);
}
#endregion
#region 读取为字符串
/// <summary>
/// 读取 <see cref="Stream"/> 中的内容,并解码为字符串。
/// 会将流的位置主动重置到开头。
/// </summary>
public static string ReadString(this Stream stream, Encoding? encoding = null) {
using var memoryStream = new MemoryStream();
if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(memoryStream);
return memoryStream.ToArray().GetString(encoding);
}
/// <summary>
/// 将 <paramref name="bytes"/> 解码为字符串。
/// </summary>
public static string GetString(this byte[] bytes, Encoding? encoding = null) {
if (encoding is not null) return encoding.GetString(bytes);
int length = bytes.Length;
// 根据 BOM 判断编码
if (length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) {
return Encoding.UTF8.GetString(bytes, 3, length - 3); // 带 BOM 的 UTF8
} else if (length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) {
return Encoding.BigEndianUnicode.GetString(bytes, 2, length - 2);
} else if (length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) {
return Encoding.Unicode.GetString(bytes, 2, length - 2);
}
// 无 BOM 文件:GB18030(ANSI)或 UTF8
try {
return new UTF8Encoding(false, true).GetString(bytes); // 不带 BOM 的 UTF8
} catch (DecoderFallbackException) {
return Encoding.GetEncoding("GB18030").GetString(bytes);
}
}
#endregion #endregion
@@ -205,13 +382,14 @@ public static class StringExtensions {
/// 过短则用 <paramref name="code"/> 将其左侧填充,过长则截取靠左的指定长度。 /// 过短则用 <paramref name="code"/> 将其左侧填充,过长则截取靠左的指定长度。
/// </summary> /// </summary>
public static string EnsureLength(this string? str, char code, int length) { public static string EnsureLength(this string? str, char code, int length) {
if (str == null) str = ""; str ??= "";
return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code); return str.Length > length ? str.Substring(0, length) : str.PadLeft(length, code);
} }
/// <summary> /// <summary>
/// 该字符串中的字符是否均为 ASCII 字符。 /// 该字符串中的字符是否均为 ASCII 字符。
/// </summary> /// </summary>
public static bool IsAsciiOnly(this string input) => input.All(c => c < 128); public static bool IsAsciiOnly(this string input)
=> input.All(c => c < 128);
} }
+31 -34
View File
@@ -1,67 +1,64 @@
namespace MeloongCore; namespace MeloongCore;
/// <summary> /// <summary>
/// 线程安全的 <see cref="List{T}"/> 实现。 /// 使用粗粒度锁的线程安全 <see cref="List{T}"/> 实现。
/// 当调用枚举器时返回一个临时副本,以避免列表在枚举过程中被修改导致异常。
/// </summary> /// </summary>
public class ConcurrentList<T> : IList<T>, IList, IEnumerable, IEnumerable<T> { public class ConcurrentList<T> : IList<T>, IList, IEnumerable, IEnumerable<T> {
private readonly List<T> _items = []; private readonly List<T> _items = [];
public readonly object syncLock = new();
// 构造函数 // 构造函数
public ConcurrentList() { } public ConcurrentList() { }
public ConcurrentList(IEnumerable<T> data) => _items = new List<T>(data); public ConcurrentList(IEnumerable<T> data) => _items = new(data);
public static implicit operator ConcurrentList<T>(List<T> data) => new(data); public static implicit operator ConcurrentList<T>(List<T> data) => new(data);
public static implicit operator List<T>(ConcurrentList<T> data) { lock (data.syncLock) { return new List<T>(data._items); } } public static implicit operator List<T>(ConcurrentList<T> data) { lock (data._syncLock) { return new(data._items); } }
// 枚举器 // 枚举器
public IEnumerator<T> GetEnumerator() { /// <summary>
lock (syncLock) { /// 返回此列表的副本。
return _items.ToList().GetEnumerator(); /// </summary>
} public IEnumerator<T> GetEnumerator() { lock (_syncLock) return _items.ToList().GetEnumerator(); }
} /// <summary>
IEnumerator IEnumerable.GetEnumerator() { /// 返回此列表的副本。
lock (syncLock) { /// </summary>
return _items.ToList().GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() { lock (_syncLock) return _items.ToList().GetEnumerator(); }
}
}
// 成员 // 成员
public int Count { get { lock (syncLock) { return _items.Count; } } } public int Count { get { lock (_syncLock) { return _items.Count; } } }
public bool IsReadOnly => false; public bool IsReadOnly => false;
bool IList.IsFixedSize => false; bool IList.IsFixedSize => false;
bool ICollection.IsSynchronized => true; bool ICollection.IsSynchronized => true;
object ICollection.SyncRoot => syncLock; private readonly object _syncLock = new();
object ICollection.SyncRoot => _syncLock;
public T this[int index] { public T this[int index] {
get { lock (syncLock) { return _items[index]; } } get { lock (_syncLock) { return _items[index]; } }
set { lock (syncLock) { _items[index] = value; } } set { lock (_syncLock) { _items[index] = value; } }
} }
object? IList.this[int index] { object? IList.this[int index] {
get => this[index]; get => this[index];
set { lock (syncLock) { _items[index] = (T) value!; } } set { lock (_syncLock) { _items[index] = (T) value!; } }
} }
public void Add(T item) { lock (syncLock) { _items.Add(item); } } public void Add(T item) { lock (_syncLock) { _items.Add(item); } }
int IList.Add(object? value) { lock (syncLock) { _items.Add((T) value!); return _items.Count - 1; } } int IList.Add(object? value) { lock (_syncLock) { _items.Add((T) value!); return _items.Count - 1; } }
public void Insert(int index, T item) { lock (syncLock) { _items.Insert(index, item); } } public void Insert(int index, T item) { lock (_syncLock) { _items.Insert(index, item); } }
void IList.Insert(int index, object? value) { lock (syncLock) { _items.Insert(index, (T) value!); } } void IList.Insert(int index, object? value) { lock (_syncLock) { _items.Insert(index, (T) value!); } }
public bool Remove(T item) { lock (syncLock) { return _items.Remove(item); } } public bool Remove(T item) { lock (_syncLock) { return _items.Remove(item); } }
void IList.Remove(object? value) { lock (syncLock) { if (value is T t) _items.Remove(t); } } void IList.Remove(object? value) { lock (_syncLock) { if (value is T t) _items.Remove(t); } }
public void RemoveAt(int index) { lock (syncLock) { _items.RemoveAt(index); } } public void RemoveAt(int index) { lock (_syncLock) { _items.RemoveAt(index); } }
public void Clear() { lock (syncLock) { _items.Clear(); } } public void Clear() { lock (_syncLock) { _items.Clear(); } }
public bool Contains(T item) { lock (syncLock) { return _items.Contains(item); } } public bool Contains(T item) { lock (_syncLock) { return _items.Contains(item); } }
bool IList.Contains(object? value) { lock (syncLock) { return value is T t && _items.Contains(t); } } bool IList.Contains(object? value) { lock (_syncLock) { return value is T t && _items.Contains(t); } }
public int IndexOf(T item) { lock (syncLock) { return _items.IndexOf(item); } } public int IndexOf(T item) { lock (_syncLock) { return _items.IndexOf(item); } }
int IList.IndexOf(object? value) { lock (syncLock) { return value is T t ? _items.IndexOf(t) : -1; } } int IList.IndexOf(object? value) { lock (_syncLock) { return value is T t ? _items.IndexOf(t) : -1; } }
public void CopyTo(T[] array, int arrayIndex) { lock (syncLock) { _items.CopyTo(array, arrayIndex); } } public void CopyTo(T[] array, int arrayIndex) { lock (_syncLock) { _items.CopyTo(array, arrayIndex); } }
void ICollection.CopyTo(Array array, int index) { lock (syncLock) { ((ICollection) _items).CopyTo(array, index); } } void ICollection.CopyTo(Array array, int index) { lock (_syncLock) { ((ICollection) _items).CopyTo(array, index); } }
} }
+231 -106
View File
@@ -6,30 +6,12 @@ namespace MeloongCore;
/// <summary> /// <summary>
/// 日志等级。 /// 日志等级。
/// </summary> /// </summary>
public enum LogLevels { public enum LogLevel { Trace, Info, Warn, Error }
/// <summary>
/// 追踪。
/// 只在调试状态下输出日志信息。
/// </summary>
Trace,
/// <summary>
/// 信息。
/// </summary>
Info,
/// <summary>
/// 警告。
/// </summary>
Warning,
/// <summary>
/// 错误。
/// </summary>
Error
}
/// <summary> /// <summary>
/// 输出日志时执行的错误汇报行为。 /// 输出日志时执行的错误汇报行为。
/// </summary> /// </summary>
public enum LogBehaviors { public enum LogBehavior {
/// <summary> /// <summary>
/// 无提示。 /// 无提示。
/// </summary> /// </summary>
@@ -59,122 +41,265 @@ public enum LogBehaviors {
public static class Logger { public static class Logger {
public static BaseLogger Instance { get; set; } = new(); public static BaseLogger Instance { get; set; } = new();
// 转发给实例的方法调用 // 转发给 BaseLogger 实例的对外方法
public static void Log(string message, LogLevels level = LogLevels.Info, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") public static void Trace(string message, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
=> Instance.Log(message, level, behavior, filePath); => Log(null, message, LogLevel.Trace, behavior, filePath);
public static void Log(Exception ex, string? message = null, LogLevels level = LogLevels.Warning, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") public static void Info(string message, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
=> Log(null, message, LogLevel.Info, behavior, filePath);
public static void Warn(string message, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "")
=> Log(null, message, LogLevel.Warn, behavior, filePath);
public static void Error(string message, LogBehavior behavior = LogBehavior.AlertThenFeedback, [CallerFilePath] string filePath = "")
=> Log(null, message, LogLevel.Error, behavior, filePath);
public static void Log(string message, LogLevel level = LogLevel.Info, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
=> Log(null, message, level, behavior, filePath);
public static void Trace(Exception ex, string? message = null, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
=> Log(ex, message, LogLevel.Trace, behavior, filePath);
public static void Info(Exception ex, string? message = null, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
=> Log(ex, message, LogLevel.Info, behavior, filePath);
public static void Warn(Exception ex, string? message = null, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "")
=> Log(ex, message, LogLevel.Warn, behavior, filePath);
public static void Error(Exception ex, string? message = null, LogBehavior behavior = LogBehavior.AlertThenFeedback, [CallerFilePath] string filePath = "")
=> Log(ex, message, LogLevel.Error, behavior, filePath);
public static void Log(Exception? ex, string? message = null, LogLevel level = LogLevel.Warn, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "")
=> Instance.Log(ex, message, level, behavior, filePath); => Instance.Log(ex, message, level, behavior, filePath);
public static void Trace(Func<string> message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") { if (Instance.MinLevel <= LogLevels.Trace) Log(message(), LogLevels.Trace, behavior, filePath); } /// <summary>
public static void Trace(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Trace, behavior, filePath); /// 在不调用 Logger 的情况下,将信息直接发送到输出窗口。
public static void Info(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Info, behavior, filePath); /// </summary>
public static void Warning(string message, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Warning, behavior, filePath); [Conditional("DEBUG")]
public static void Error(string message, LogBehaviors behavior = LogBehaviors.AlertThenFeedback, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Error, behavior, filePath); public static void SendToDebug(string message, LogLevel level = LogLevel.Error, [CallerFilePath] string filePath = "")
=> Debug.WriteLine($"{BaseLogger.GetLogPrefix(level, filePath)}{message}");
/// <summary>
/// 在不调用 Logger 的情况下,将信息直接发送到输出窗口。
/// </summary>
[Conditional("DEBUG")]
public static void SendToDebug(Exception ex, string? message = null, LogLevel level = LogLevel.Error, [CallerFilePath] string filePath = "")
=> Debug.WriteLine($"{BaseLogger.GetLogPrefix(level, filePath)}{(message is null ? "" : $"{message}:")}{ex.GetDisplay(true)}");
#region 内插优化
// VB.NET:由于不兼容 InterpolatedStringHandler,只能手动使用 Lambda
public static void Log(Func<string?> messageFactory, LogLevel level = LogLevel.Info, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "") {
if (Instance.MinLevel > level) return;
Instance.Log(null, messageFactory() ?? string.Empty, level, behavior, filePath);
}
public static void Trace(Func<string?> messageFactory, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
=> Log(messageFactory, LogLevel.Trace, behavior, filePath);
public static void Info(Func<string?> messageFactory, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "")
=> Log(messageFactory, LogLevel.Info, behavior, filePath);
public static void Warn(Func<string?> messageFactory, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "")
=> Log(messageFactory, LogLevel.Warn, behavior, filePath);
public static void Error(Func<string?> messageFactory, LogBehavior behavior = LogBehavior.AlertThenFeedback, [CallerFilePath] string filePath = "")
=> Log(messageFactory, LogLevel.Error, behavior, filePath);
// C#:仅当实际需要输出日志时,才格式化内插字符串,以优化性能
public static void Log(LogLevel level, [InterpolatedStringHandlerArgument("level")] ref LogInterpolatedStringHandler handler, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "") {
if (handler.isEnabled) Instance.Log(null, handler.ToStringAndClear(), level, behavior, filePath);
}
public static void Trace(ref LogInterpolatedStringHandler<TraceLogLevel> handler, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "") {
if (handler.IsEnabled) Instance.Log(null, handler.ToStringAndClear(), LogLevel.Trace, behavior, filePath);
}
public static void Info(ref LogInterpolatedStringHandler<InfoLogLevel> handler, LogBehavior behavior = LogBehavior.None, [CallerFilePath] string filePath = "") {
if (handler.IsEnabled) Instance.Log(null, handler.ToStringAndClear(), LogLevel.Info, behavior, filePath);
}
public static void Warn(ref LogInterpolatedStringHandler<WarnLogLevel> handler, LogBehavior behavior = LogBehavior.ToastIfDebug, [CallerFilePath] string filePath = "") {
if (handler.IsEnabled) Instance.Log(null, handler.ToStringAndClear(), LogLevel.Warn, behavior, filePath);
}
public static void Error(ref LogInterpolatedStringHandler<ErrorLogLevel> handler, LogBehavior behavior = LogBehavior.AlertThenFeedback, [CallerFilePath] string filePath = "") {
if (handler.IsEnabled) Instance.Log(null, handler.ToStringAndClear(), LogLevel.Error, behavior, filePath);
}
[InterpolatedStringHandler]
public ref struct LogInterpolatedStringHandler {
private StringBuilder? _sb;
public readonly bool isEnabled;
public LogInterpolatedStringHandler(int literalLength, int formattedCount, LogLevel level, out bool isEnabled) {
this.isEnabled = isEnabled = Logger.Instance.MinLevel <= level;
_sb = this.isEnabled ? new StringBuilder(literalLength) : null;
}
public void AppendLiteral(string value) => _sb?.Append(value);
public void AppendFormatted<T>(T value) => _sb?.Append(value?.ToString());
public void AppendFormatted<T>(T value, string? format) => _sb?.Append(value is IFormattable formattable ? formattable.ToString(format, null) : value?.ToString());
public void AppendFormatted<T>(T value, int alignment) {
if (_sb is null) return;
var s = value?.ToString() ?? string.Empty;
_sb.Append(alignment > 0 ? s.PadLeft(alignment) : alignment < 0 ? s.PadRight(-alignment) : s);
}
public void AppendFormatted<T>(T value, int alignment, string? format) {
if (_sb is null) return;
var s = value is IFormattable formattable ? formattable.ToString(format, null) : value?.ToString() ?? string.Empty;
_sb.Append(alignment > 0 ? s.PadLeft(alignment) : alignment < 0 ? s.PadRight(-alignment) : s);
}
public void AppendFormatted(string? value) => _sb?.Append(value);
public void AppendFormatted(object? value, int alignment = 0, string? format = null) {
if (_sb is null) return;
var s = value is IFormattable formattable ? formattable.ToString(format, null) : value?.ToString() ?? string.Empty;
_sb.Append(alignment > 0 ? s.PadLeft(alignment) : alignment < 0 ? s.PadRight(-alignment) : s);
}
internal string ToStringAndClear() {
var result = _sb?.ToString() ?? string.Empty;
_sb = null;
return result;
}
}
[InterpolatedStringHandler]
public ref struct LogInterpolatedStringHandler<TLevel> where TLevel : struct, ILogLevelProvider {
private LogInterpolatedStringHandler _inner;
public bool IsEnabled => _inner.isEnabled;
public LogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) => _inner = new(literalLength, formattedCount, default(TLevel).Level, out isEnabled);
public void AppendLiteral(string value) => _inner.AppendLiteral(value);
public void AppendFormatted<T>(T value) => _inner.AppendFormatted(value);
public void AppendFormatted<T>(T value, string? format) => _inner.AppendFormatted(value, format);
public void AppendFormatted<T>(T value, int alignment) => _inner.AppendFormatted(value, alignment);
public void AppendFormatted<T>(T value, int alignment, string? format) => _inner.AppendFormatted(value, alignment, format);
public void AppendFormatted(string? value) => _inner.AppendFormatted(value);
public void AppendFormatted(object? value, int alignment = 0, string? format = null) => _inner.AppendFormatted(value, alignment, format);
internal string ToStringAndClear() => _inner.ToStringAndClear();
}
public readonly struct TraceLogLevel : ILogLevelProvider { public LogLevel Level => LogLevel.Trace; }
public readonly struct InfoLogLevel : ILogLevelProvider { public LogLevel Level => LogLevel.Info; }
public readonly struct WarnLogLevel : ILogLevelProvider { public LogLevel Level => LogLevel.Warn; }
public readonly struct ErrorLogLevel : ILogLevelProvider { public LogLevel Level => LogLevel.Error; }
public interface ILogLevelProvider { LogLevel Level { get; } }
#endregion
public static void Trace(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Trace, behavior, filePath);
public static void Info(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Info, behavior, filePath);
public static void Warning(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Warning, behavior, filePath);
public static void Error(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.AlertThenFeedback, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Error, behavior, filePath);
} }
/// <summary> /// <summary>
/// 最基础的日志实现。 /// 最基础的日志实现。
/// 仅将日志输出到 <see cref="Debug"/>,不实现 <see cref="LogBehaviors"/>。 /// 仅将日志输出到 <see cref="Debug"/>,不实现 <see cref="LogBehavior"/>。
/// </summary> /// </summary>
public class BaseLogger { public class BaseLogger {
/// <summary> /// <summary>
/// 最低日志输出等级,低于此等级的日志将被忽略。 /// 最低日志输出等级,低于此等级的日志将被忽略。
/// </summary> /// </summary>
public LogLevels MinLevel { get; set; } = LogLevels.Trace; public LogLevel MinLevel { get; set; } = LogLevel.Trace;
// 核心方法 // 核心方法
public virtual void Log(string message, LogLevels level, LogBehaviors behavior, string filePath) { public virtual void Log(Exception? ex, string? message, LogLevel level, LogBehavior behavior, string filePath) {
if (MinLevel > level) return; if (ex is ThreadInterruptedException) {
try { Thread.CurrentThread.Interrupt();
var formattedMessage = Format(message, level, filePath, null); return;
Output(formattedMessage, level);
HandleBehavior(message, formattedMessage, behavior, null);
} catch {}
} }
public virtual void Log(Exception ex, string? message, LogLevels level, LogBehaviors behavior, string filePath) {
if (MinLevel > level) return; if (MinLevel > level) return;
if (ex is ThreadInterruptedException) return;
try { try {
var formattedMessage = (message is null ? "" : $"{message}:") + ex.GetDisplay(true); // 格式化文本
var formattedMessage = ex is null ?
(message ?? "") :
(message is null ? "" : $"{message}:") + ex.GetDisplay(true);
formattedMessage = Format(formattedMessage, level, filePath, ex); formattedMessage = Format(formattedMessage, level, filePath, ex);
Output(formattedMessage, level); // 将格式化后的日志文本置入缓冲区
if (avaliable || queue.Count < 100) { // 在初始化前保留至多 100 条日志
queue.Enqueue(new(level, formattedMessage));
queuedEvent.Set();
}
// 执行事件
HandleBehavior(message, formattedMessage, behavior, ex); HandleBehavior(message, formattedMessage, behavior, ex);
} catch { } } catch (Exception logEx) {
Logger.SendToDebug(logEx, "打印日志失败");
}
} }
/// <summary> /// <summary>
/// 格式化日志文本。 /// 格式化日志文本。
/// </summary> /// </summary>
protected virtual string Format(string text, LogLevels level, string filePath, Exception? ex) { public virtual string Format(string text, LogLevel level, string filePath, Exception? ex) {
string prefix = $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {(Thread.CurrentThread.Name is null ? "" : $"<{Thread.CurrentThread.Name}> ")}[{filePath.AfterLast(@"\").BeforeFirst(".")}] "; string prefix = GetLogPrefix(level, filePath);
if (string.IsNullOrEmpty(text)) return prefix;
return text return text
.ReplaceLineEndings("\n", mergeMultiple: true).Split(['\n'], StringSplitOptions.RemoveEmptyEntries) .ReplaceLineEndings("\n", mergeMultiple: true).Split('\n', true)
.Select(t => prefix + t) .Select(t => prefix + t)
.Join("\r\n"); .Join("\r\n");
} }
public static string GetLogPrefix(LogLevel level, string filePath)
=> $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {(Thread.CurrentThread.Name is null ? "" : $"<{Thread.CurrentThread.Name}> ")}[{PathUtils.GetLastPart(filePath).BeforeFirst(".")}] ";
/// <summary>
/// 执行 <see cref="LogBehavior"/>。
/// </summary>
public virtual void HandleBehavior(string? rawMessage, string formattedMessage, LogBehavior behavior, Exception? ex) {
}
/// <summary> /// <summary>
/// 输出格式化后的日志文本。 /// 输出格式化后的日志文本。
/// </summary> /// </summary>
protected virtual void Output(string formattedMessage, LogLevels level) { public virtual void Output(LogEntry entry) {
Debug.WriteLine(formattedMessage); Debug.WriteLine(entry.message);
} }
/// <summary> public virtual void Init() { }
/// 在调用 Log 方法的线程执行 <see cref="LogBehaviors"/>。
/// </summary>
protected virtual void HandleBehavior(string? rawMessage, string formattedMessage, LogBehaviors behavior, Exception? ex) {
}
} #region 缓冲区与初始化
/// <summary> internal volatile bool avaliable = false;
/// 将日志输出到 <see cref="Debug"/> 并写入指定的文件夹,最多保留 5 个文件。 public record struct LogEntry(LogLevel Level, string message);
/// 不实现 <see cref="LogBehaviors"/>。 internal readonly ConcurrentQueue<LogEntry> queue = new();
/// </summary> internal readonly AutoResetEvent queuedEvent = new(false);
public class FileLogger : BaseLogger {
/// <inheritdoc/>
protected override void Output(string formattedText, LogLevels level) {
base.Output(formattedText, level);
if (!writerAvaliable && queue.Count >= 100) return; // 在 writer 就绪前,最多缓存 100 条日志
queue.Enqueue(formattedText);
queuedEvent.Set();
}
private readonly ConcurrentQueue<string> queue = new();
private readonly AutoResetEvent queuedEvent = new(false);
private StreamWriter? writer;
private volatile bool writerAvaliable = false;
/// <summary>
/// 将日志立即写入文件。
/// 不会抛出异常。
/// </summary>
public void Flush() {
try {
if (writer is null || !writerAvaliable) return;
lock (flushLock)
while (queue.TryDequeue(out string line)) writer.WriteLine(line); // writer 指定了 AutoFlush
} catch { }
}
private readonly object flushLock = new();
/// <summary> /// <summary>
/// 初始化此 Logger。 /// 初始化此 Logger。
/// 会在新线程中,将之前的日志文件依次后移,最多保留 5 个文件。 /// 会在新线程中,将之前的日志文件依次后移,最多保留 5 个文件。
/// </summary> /// </summary>
public FileLogger(string logFolder, string fileNamePrefix = "Log", string fileNameSuffix = ".txt") { public BaseLogger() {
var thread = new Thread(() => { var thread = new Thread(() => {
try {
Init();
avaliable = true;
Logger.Info($"{GetType().Name} 日志初始化结束");
while (avaliable) {
queuedEvent.WaitOne();
Flush();
}
} catch (Exception ex) {
avaliable = false;
Logger.SendToDebug(ex, "基础日志线程出错");
}
}) { Name = nameof(Logger), Priority = ThreadPriority.Lowest, IsBackground = true };
thread.Start();
}
/// <summary>
/// 立即输出缓冲区的日志。
/// 不会抛出异常。
/// </summary>
public void Flush() {
try {
if (!avaliable) return;
lock (flushLock)
while (queue.TryDequeue(out LogEntry entry)) Output(entry); // writer 指定了 AutoFlush
} catch (Exception logEx) {
Logger.SendToDebug(logEx, "输出日志失败");
}
}
private readonly object flushLock = new();
#endregion
}
/// <summary>
/// 将日志输出到 <see cref="Debug"/> 并写入指定的文件夹,最多保留 5 个文件。
/// 不实现 <see cref="LogBehavior"/>。
/// </summary>
public class FileLogger : BaseLogger, IDisposable {
public string logFolder = Path.Combine(PathUtils.CurrentFolder, "logs");
public string fileNamePrefix = "Log";
public string fileNameSuffix = ".txt";
private StreamWriter? writer;
/// <inheritdoc/>
public override void Init() {
// 轮转日志文件,将 Log1.txt 留空 // 轮转日志文件,将 Log1.txt 留空
Logger.Info("日志初始化开始"); Logger.Info("开始轮转日志文件");
try { try {
for (int i = 4; i >= 1; i--) { for (int i = 4; i >= 1; i--) {
string newerFile = Path.Combine(logFolder, $"{fileNamePrefix}{i + 1}{fileNameSuffix}"); string newerFile = Path.Combine(logFolder, $"{fileNamePrefix}{i + 1}{fileNameSuffix}");
@@ -184,25 +309,25 @@ public class FileLogger : BaseLogger {
FileUtils.Delete(olderFile); FileUtils.Delete(olderFile);
} }
} catch (IOException ex) { } catch (IOException ex) {
Logger.Warning(ex, "可能同时开启了多个程序,这或许会导致未知问题", LogBehaviors.Toast); Logger.Warn(ex, "可能同时开启了多个程序,这或许会导致未知问题", LogBehavior.Toast);
} catch (Exception ex) { } catch (Exception ex) {
Logger.Warning(ex, "整理日志文件失败"); Logger.Warn(ex, "整理日志文件失败");
} }
// 写入新日志文件 // 新建 writer
try { writer = new StreamWriter(PathUtils.ForApi(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true };
writer = new StreamWriter(PathUtils.WithLongPath(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true };
writerAvaliable = true;
Logger.Info("日志初始化成功");
while (true) {
queuedEvent.WaitOne();
Flush();
} }
} catch (Exception ex) {
Logger.Warning(ex, "写入日志文件失败", LogBehaviors.Toast); /// <inheritdoc/>
writerAvaliable = false; public override void Output(LogEntry entry) {
base.Output(entry);
writer?.WriteLine(entry.message); // writer 指定了 AutoFlush
} }
}) { Name = nameof(FileLogger), Priority = ThreadPriority.Lowest, IsBackground = true };
thread.Start(); public void Dispose() {
avaliable = false;
if (writer is not null) ((IDisposable) writer).Dispose();
queuedEvent.Dispose();
GC.SuppressFinalize(this);
} }
} }
+5 -5
View File
@@ -15,12 +15,12 @@ public static class MsDelta {
public static void Create(string oldFilePath, string newFilePath, string deltaFilePath) { public static void Create(string oldFilePath, string newFilePath, string deltaFilePath) {
if (!FileUtils.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath); if (!FileUtils.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath);
if (!FileUtils.Exists(newFilePath)) throw new FileNotFoundException($"新文件不存在:{newFilePath}", newFilePath); if (!FileUtils.Exists(newFilePath)) throw new FileNotFoundException($"新文件不存在:{newFilePath}", newFilePath);
DirectoryUtils.Create(deltaFilePath, isFilePath: true); DirectoryUtils.Create(PathUtils.RemoveLastPart(deltaFilePath));
Logger.Info($"正在生成补丁:{oldFilePath} → {newFilePath},补丁文件将输出到:{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) // 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 // 131072L: IgnoreFileSizeLimit, 32u: Crc32
if (!CreateDelta(15L, 131072L, 0L, if (!CreateDelta(15L, 131072L, 0L,
PathUtils.WithLongPath(oldFilePath), PathUtils.WithLongPath(newFilePath), null, null, new DeltaInput(), IntPtr.Zero, 32u, PathUtils.WithLongPath(deltaFilePath))) PathUtils.ForApi(oldFilePath), PathUtils.ForApi(newFilePath), null, null, new DeltaInput(), IntPtr.Zero, 32u, PathUtils.ForApi(deltaFilePath)))
throw new Win32Exception(); throw new Win32Exception();
} }
@@ -32,14 +32,14 @@ public static class MsDelta {
public static void Apply(string oldFilePath, string deltaFilePath, string newFilePath) { public static void Apply(string oldFilePath, string deltaFilePath, string newFilePath) {
if (!FileUtils.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath); if (!FileUtils.Exists(oldFilePath)) throw new FileNotFoundException($"旧文件不存在:{oldFilePath}", oldFilePath);
if (!FileUtils.Exists(deltaFilePath)) throw new FileNotFoundException($"补丁文件不存在:{deltaFilePath}", deltaFilePath); if (!FileUtils.Exists(deltaFilePath)) throw new FileNotFoundException($"补丁文件不存在:{deltaFilePath}", deltaFilePath);
DirectoryUtils.Create(newFilePath, isFilePath: true); DirectoryUtils.Create(PathUtils.RemoveLastPart(newFilePath));
Logger.Info($"正在应用补丁:原始文件 {oldFilePath} + 补丁文件 {deltaFilePath} → 输出至 {newFilePath}"); Logger.Info($"正在应用补丁:原始文件 {oldFilePath} + 补丁文件 {deltaFilePath} → 输出至 {newFilePath}");
// 1L: AllowLegacy // 1L: AllowLegacy
if (!ApplyDelta(1L, PathUtils.WithLongPath(oldFilePath), PathUtils.WithLongPath(deltaFilePath), PathUtils.WithLongPath(newFilePath))) if (!ApplyDelta(1L, PathUtils.ForApi(oldFilePath), PathUtils.ForApi(deltaFilePath), PathUtils.ForApi(newFilePath)))
throw new Win32Exception(); throw new Win32Exception();
} }
// API
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
private struct DeltaInput { private struct DeltaInput {
public IntPtr Start; public IntPtr Start;
+13 -6
View File
@@ -1,6 +1,6 @@
namespace MeloongCore; namespace MeloongCore;
public readonly struct OneOf<T0, T1> { public readonly struct OneOf<T0, T1> {
private readonly int _index; private readonly int _index = -1; // -1 表示未初始化(这是一个 struct,所以这可以让默认值不为 0)
private readonly T0? _value0; private readonly T0? _value0;
private readonly T1? _value1; private readonly T1? _value1;
public static implicit operator OneOf<T0, T1>(T0 value) => new(0, value, default); public static implicit operator OneOf<T0, T1>(T0 value) => new(0, value, default);
@@ -17,7 +17,9 @@ public readonly struct OneOf<T0, T1> {
/// 对不同类型执行不同的操作,并返回同一个值。 /// 对不同类型执行不同的操作,并返回同一个值。
/// </summary> /// </summary>
public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1) => _index switch { public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1) => _index switch {
0 => f0(_value0!), _ => f1(_value1!) 0 => f0(_value0!),
1 => f1(_value1!),
_ => throw new InvalidOperationException()
}; };
/// <summary> /// <summary>
/// 对不同类型执行不同的操作。 /// 对不同类型执行不同的操作。
@@ -25,6 +27,7 @@ public readonly struct OneOf<T0, T1> {
public void Switch(Action<T0> f0, Action<T1> f1) { public void Switch(Action<T0> f0, Action<T1> f1) {
if (_index == 0) f0(_value0!); if (_index == 0) f0(_value0!);
else if (_index == 1) f1(_value1!); else if (_index == 1) f1(_value1!);
else throw new InvalidOperationException();
} }
/// <summary> /// <summary>
/// 判断当前的类型是否为 T。 /// 判断当前的类型是否为 T。
@@ -36,7 +39,7 @@ public readonly struct OneOf<T0, T1> {
}; };
/// <summary> /// <summary>
/// 假定当前的类型为 T,并返回该值。 /// 假定当前的类型为 T,并返回该值。
/// 若当前值的类型不为 T,则抛出 InvalidOperationException。 /// 若当前值的类型不为 T,则抛出 <see cref="InvalidOperationException"/>。
/// </summary> /// </summary>
public T As<T>() => _index switch { public T As<T>() => _index switch {
0 when typeof(T) == typeof(T0) => (T)(object)_value0!, 0 when typeof(T) == typeof(T0) => (T)(object)_value0!,
@@ -46,7 +49,7 @@ public readonly struct OneOf<T0, T1> {
} }
public readonly struct OneOf<T0, T1, T2> { public readonly struct OneOf<T0, T1, T2> {
private readonly int _index; private readonly int _index = -1; // -1 表示未初始化(这是一个 struct,所以这可以让默认值不为 0)
private readonly T0? _value0; private readonly T0? _value0;
private readonly T1? _value1; private readonly T1? _value1;
private readonly T2? _value2; private readonly T2? _value2;
@@ -67,7 +70,10 @@ public readonly struct OneOf<T0, T1, T2> {
/// 对不同类型执行不同的操作,并返回同一个值。 /// 对不同类型执行不同的操作,并返回同一个值。
/// </summary> /// </summary>
public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2) => _index switch { public TResult Switch<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2) => _index switch {
0 => f0(_value0!), 1 => f1(_value1!), _ => f2(_value2!) 0 => f0(_value0!),
1 => f1(_value1!),
2 => f2(_value2!),
_ => throw new InvalidOperationException()
}; };
/// <summary> /// <summary>
/// 对不同类型执行不同的操作。 /// 对不同类型执行不同的操作。
@@ -76,6 +82,7 @@ public readonly struct OneOf<T0, T1, T2> {
if (_index == 0) f0(_value0!); if (_index == 0) f0(_value0!);
else if (_index == 1) f1(_value1!); else if (_index == 1) f1(_value1!);
else if (_index == 2) f2(_value2!); else if (_index == 2) f2(_value2!);
else throw new InvalidOperationException();
} }
/// <summary> /// <summary>
/// 判断当前的类型是否为 T。 /// 判断当前的类型是否为 T。
@@ -88,7 +95,7 @@ public readonly struct OneOf<T0, T1, T2> {
}; };
/// <summary> /// <summary>
/// 假定当前的类型为 T,并返回该值。 /// 假定当前的类型为 T,并返回该值。
/// 若当前值的类型不为 T,则抛出 InvalidOperationException。 /// 若当前值的类型不为 T,则抛出 <see cref="InvalidOperationException"/>。
/// </summary> /// </summary>
public T As<T>() => _index switch { public T As<T>() => _index switch {
0 when typeof(T) == typeof(T0) => (T) (object) _value0!, 0 when typeof(T) == typeof(T0) => (T) (object) _value0!,
+9
View File
@@ -0,0 +1,9 @@
namespace MeloongCore;
public static class Main {
public static void Init(BaseLogger? logger = null) {
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(2));
if (logger != null) Logger.Instance = logger;
}
}
+118 -33
View File
@@ -5,77 +5,162 @@ public static class DirectoryUtils {
/// 创建文件夹,或文件所在的文件夹。 /// 创建文件夹,或文件所在的文件夹。
/// 文件夹已存在时不会抛出异常。 /// 文件夹已存在时不会抛出异常。
/// </summary> /// </summary>
public static void Create(string path, bool isFilePath = false) { public static void Create(string path) {
if (isFilePath) path = Path.GetDirectoryName(path); if (DirectoryUtils.Exists(path)) return;
if (Exists(path)) return;
Logger.Trace($"新建文件夹:{path}"); Logger.Trace($"新建文件夹:{path}");
path = PathUtils.WithLongPath(path); Directory.CreateDirectory(PathUtils.ForApi(path));
Directory.CreateDirectory(path); }
/// <summary>
/// 在临时文件夹下创建一个随机名称的文件夹,并返回其路径。
/// </summary>
public static string CreateRandom() {
var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
DirectoryUtils.Create(tempDir);
return tempDir;
} }
/// <summary> /// <summary>
/// 判断文件夹是否存在。 /// 判断文件夹是否存在。
/// </summary> /// </summary>
public static bool Exists(string path) { public static bool Exists(string path)
return Directory.Exists(PathUtils.WithLongPath(path)); => Directory.Exists(PathUtils.ForApi(path));
}
/// <summary> /// <summary>
/// 创建 <see cref="DirectoryInfo"/> 对象。 /// 获取 <see cref="DirectoryInfo"/> 对象。
/// </summary> /// </summary>
public static DirectoryInfo GetInfo(string path) { public static DirectoryInfo GetInfo(string path)
return new(PathUtils.WithLongPath(path)); => new(PathUtils.ForApi(path));
}
/// <summary> /// <summary>
/// 返回指定路径下的所有文件,不以 \\?\ 开头。 /// 返回指定路径下的所有文件,不以 \\?\ 开头。
/// 如果文件夹不存在,返回空列表。
/// </summary> /// </summary>
public static IEnumerable<string> GetFiles(string path, bool topDirectoryOnly = false, string searchPattern = "*") { public static IEnumerable<string> GetFiles(string path, bool topDirectoryOnly = false, string searchPattern = "*") {
if (!Exists(path)) return []; if (!DirectoryUtils.Exists(path)) return [];
Logger.Trace($"枚举文件({searchPattern},递归:{!topDirectoryOnly}):{path}"); return Directory.EnumerateFiles(PathUtils.ForApi(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories).
return Directory.EnumerateFiles(PathUtils.WithLongPath(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories). Select(PathUtils.RemoveExtendedPrefix);
Select(PathUtils.WithoutLongPath);
} }
/// <summary> /// <summary>
/// 返回指定路径下的所有文件夹,不以分隔符结尾,不以 \\?\ 开头。 /// 返回指定路径下的所有文件夹,不以分隔符结尾,不以 \\?\ 开头。
/// 如果文件夹不存在,返回空列表。
/// </summary> /// </summary>
public static IEnumerable<string> GetDirectories(string path, bool topDirectoryOnly = false, string searchPattern = "*") { public static IEnumerable<string> GetDirectories(string path, bool topDirectoryOnly = false, string searchPattern = "*") {
if (!Exists(path)) return []; if (!DirectoryUtils.Exists(path)) return [];
Logger.Trace($"枚举文件夹({searchPattern},递归:{!topDirectoryOnly}):{path}"); return Directory.EnumerateDirectories(PathUtils.ForApi(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories).
return Directory.EnumerateDirectories(PathUtils.WithLongPath(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories). Select(PathUtils.RemoveExtendedPrefix);
Select(PathUtils.WithoutLongPath);
} }
/// <summary> /// <summary>
/// 该文件夹是否为空。 /// 该文件夹是否为空。
/// 如果文件夹不存在,也返回 true。 /// 如果文件夹不存在,返回 true。
/// </summary> /// </summary>
public static bool IsEmpty(string path) { public static bool IsEmpty(string path) {
if (!Exists(path)) return true; if (!DirectoryUtils.Exists(path)) return true;
return !Directory.EnumerateFileSystemEntries(PathUtils.WithLongPath(path)).Any(); return !Directory.EnumerateFileSystemEntries(PathUtils.ForApi(path)).Any();
}
/// <summary>
/// 复制文件夹。
/// 若复制自身到自身,则不执行操作;若仅大小写不同,则重命名此文件夹。
/// </summary>
public static void Copy(string sourceFolder, string destFolder) {
sourceFolder = PathUtils.ForCompare(sourceFolder);
destFolder = PathUtils.ForCompare(destFolder);
if (string.Compare(sourceFolder, destFolder, ignoreCase: false) == 0) {
// 复制自身到自身,则不执行操作
Logger.Trace($"复制文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
} else if (string.Compare(sourceFolder, destFolder, ignoreCase: true) == 0) {
// 路径仅大小写不同,等效于重命名
Logger.Trace($"复制文件夹到自身,但大小写不同,等效于重命名文件夹:{sourceFolder} → {destFolder}");
DirectoryUtils.Move(sourceFolder, destFolder);
} else {
// 实际的复制
Logger.Trace($"复制文件夹:{sourceFolder} → {destFolder}");
foreach (var file in DirectoryUtils.GetFiles(sourceFolder)) FileUtils.Copy(file, file.Replace(sourceFolder, destFolder));
}
} }
/// <summary> /// <summary>
/// 剪切文件夹。 /// 剪切文件夹。
/// 会创建对应文件夹、覆盖已有的文件夹。
/// </summary> /// </summary>
public static void Move(string sourceDirName, string destDirName) { public static void Move(string sourceFolder, string destFolder) {
if (!Exists(sourceDirName)) return; SafetyCheck(sourceFolder);
Create(destDirName); sourceFolder = PathUtils.ForCompare(sourceFolder);
Logger.Trace($"剪切文件夹:{sourceDirName} → {destDirName}"); destFolder = PathUtils.ForCompare(destFolder);
Directory.Move(PathUtils.WithLongPath(sourceDirName), PathUtils.WithLongPath(destDirName)); if (string.Compare(sourceFolder, destFolder, ignoreCase: false) == 0) {
// 剪切自身到自身,则不执行操作
Logger.Trace($"剪切文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
} else if (string.Compare(sourceFolder, destFolder, ignoreCase: true) == 0) {
// 路径仅大小写不同
Logger.Trace($"剪切文件夹到自身,但大小写不同:{sourceFolder} → {destFolder}");
var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFolder), Path.GetRandomFileName());
DirectoryUtils.Move(sourceFolder, temp);
DirectoryUtils.Move(temp, destFolder);
} else if (PathUtils.GetDiskName(sourceFolder) == PathUtils.GetDiskName(destFolder)) {
// 同一磁盘剪切,直接调用 Move(这只修改文件夹名,效率更高)
Logger.Trace($"剪切文件夹到同一磁盘:{sourceFolder} → {destFolder}");
DirectoryUtils.Delete(destFolder); // Move 要求此前不存在对应文件夹
ResilientUtils.RetryOn<IOException>(()
=> Directory.Move(PathUtils.ForApi(sourceFolder), PathUtils.ForApi(destFolder)));
} else {
// 不同磁盘,必须先复制再删除,这就是我们傻逼微软
Logger.Trace($"剪切文件夹到不同磁盘:{sourceFolder} → {destFolder}");
DirectoryUtils.Copy(sourceFolder, destFolder);
DirectoryUtils.Delete(sourceFolder);
}
} }
/// <summary> /// <summary>
/// 删除文件夹。 /// 删除文件夹。
/// </summary> /// </summary>
public static void Delete(string dirPath, bool toRecycleBin = false) { public static void Delete(string folder, bool toRecycleBin = false) {
if (!Exists(dirPath)) return; if (!DirectoryUtils.Exists(folder)) return;
Logger.Trace($"{(toRecycleBin ? "将文件夹删除到回收站" : "删除文件夹")}:{dirPath}"); Logger.Trace($"{(toRecycleBin ? "将文件夹删除到回收站" : "删除文件夹")}:{folder}");
SafetyCheck(folder);
// 删除
if (toRecycleBin) { if (toRecycleBin) {
FileUtils.DeleteToRecycleBin(dirPath); FileUtils.DeleteToRecycleBin(folder); // 删除到回收站
} else { } else {
Directory.Delete(PathUtils.WithLongPath(dirPath)); 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;
} }
} }
}
}
}
/// <summary>
/// 进行安全检查:若尝试操作桌面、文档、下载、Windows、当前程序所在文件夹,则抛出异常。
/// </summary>
/// <exception cref="UnauthorizedAccessException" />
private static void SafetyCheck(string folder) {
folder = PathUtils.ForCompare(folder);
if (folder == PathUtils.ForCompare(Path.GetPathRoot(folder)))
throw new UnauthorizedAccessException($"不应操作磁盘根目录:{folder}");
if (criticalFolders.Value.Any(f => f.StartsWithF(folder, ignoreCase: true)))
throw new UnauthorizedAccessException($"不应操作文件夹:{folder}");
}
private static readonly Lazy<HashSet<string>> criticalFolders = new(() => new(new[] {
PathUtils.CurrentFolder,
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
Environment.GetFolderPath(Environment.SpecialFolder.Windows),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads") // 下载文件夹没有 SpecialFolder 枚举
}.Select(f => PathUtils.ForCompare(f))));
} }
+34
View File
@@ -0,0 +1,34 @@
using System.Collections.Concurrent;
using System.Globalization;
namespace MeloongCore;
public static class EnumUtils {
/// <summary>
/// 获取枚举的所有值。
/// </summary>
private static IEnumerable<T> GetAllValues<T>() where T : struct, Enum
=> Enum.GetValues(typeof(T)).Cast<T>();
/// <summary>
/// 对于具有 <see cref="FlagsAttribute"/> 的枚举,返回其所有 Flag 值。
/// 建议仅对没有极端值的正数枚举使用。
/// </summary>
/// <remarks>
/// 会跳过:0、非 2 的幂的值、不在枚举值中的数、组合值、对应同一个枚举项的多个别名。
/// </remarks>
public static List<T> GetAllFlags<T>() where T : struct, Enum {
if (allFlagsCache.TryGetValue(typeof(T), out var cached)) return cached.Cast<T>().ToList();
if (!typeof(T).IsDefined(typeof(FlagsAttribute), inherit: false)) throw new ArgumentException($"枚举 {typeof(T).FullName} 没有定义 FlagsAttribute。");
var flags = new List<T>();
foreach (var element in EnumUtils.GetAllValues<T>().Distinct()) {
var number = Convert.ToInt64(element, CultureInfo.InvariantCulture);
if (number == 0 || (number & (number - 1)) != 0) continue; // 跳过 0 和非 2 的幂的值
flags.Add(element);
}
allFlagsCache[typeof(T)] = flags.Cast<Enum>().ToList();
return flags;
}
private static readonly ConcurrentDictionary<Type, List<Enum>> allFlagsCache = new();
}
+34 -19
View File
@@ -4,10 +4,9 @@ namespace MeloongCore;
public static class EscapeUtils { public static class EscapeUtils {
/// <summary> /// <summary>
/// XML 转义。 /// WPF XML 转义。
/// </summary> /// </summary>
public static string? XmlEscape(string? str) { public static string XmlEscape(string str) {
if (str is null) return null;
if (str.StartsWithF("{")) str = "{}" + str; // #4187 if (str.StartsWithF("{")) str = "{}" + str; // #4187
return str return str
.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;") .Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;")
@@ -30,51 +29,67 @@ public static class EscapeUtils {
} }
/// <summary> /// <summary>
/// 正则表达式转义。等同于 Regex.Escape。 /// 正则表达式转义。
/// 等同于 <see cref="Regex.Escape"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexEscape(string? value) => Regex.Escape(value); public static string RegexEscape(string value)
=> Regex.Escape(value);
/// <summary> /// <summary>
/// 正则表达式去转义。等同于 Regex.Unescape。 /// 正则表达式去转义。
/// 等同于 <see cref="Regex.Unescape"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? RegexUnescape(string? value) => Regex.Unescape(value); public static string RegexUnescape(string value)
=> Regex.Unescape(value);
/// <summary> /// <summary>
/// URL 转义。等同于 Uri.EscapeDataString。 /// URL 转义。
/// 等同于 <see cref="Uri.EscapeDataString"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlEscape(string? value) => Uri.EscapeDataString(value); public static string UrlEscape(string value)
=> Uri.EscapeDataString(value);
/// <summary> /// <summary>
/// URL 去转义。等同于 Uri.UnescapeDataString。 /// URL 去转义。
/// 等同于 <see cref="Uri.UnescapeDataString"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? UrlUnescape(string? value) => Uri.UnescapeDataString(value); public static string UrlUnescape(string value)
=> Uri.UnescapeDataString(value);
/// <summary> /// <summary>
/// 表单转义。等同于 WebUtility.UrlEncode。 /// 表单转义。
/// 等同于 <see cref="WebUtility.UrlEncode"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlEscape(string? value) => WebUtility.UrlEncode(value); public static string FormUrlEscape(string value)
=> WebUtility.UrlEncode(value);
/// <summary> /// <summary>
/// 表单去转义。等同于 WebUtility.UrlDecode。 /// 表单去转义。
/// 等同于 <see cref="WebUtility.UrlDecode"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? FormUrlUnescape(string? value) => WebUtility.UrlDecode(value); public static string FormUrlUnescape(string value)
=> WebUtility.UrlDecode(value);
/// <summary> /// <summary>
/// HTML 转义。等同于 WebUtility.HtmlEncode。 /// HTML 转义。
/// 等同于 <see cref="WebUtility.HtmlEncode"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlEscape(string? value) => WebUtility.HtmlEncode(value); public static string HtmlEscape(string value)
=> WebUtility.HtmlEncode(value);
/// <summary> /// <summary>
/// HTML 去转义。等同于 WebUtility.HtmlDecode。 /// HTML 去转义。
/// 等同于 <see cref="WebUtility.HtmlDecode"/>。
/// </summary> /// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string? HtmlUnescape(string? value) => WebUtility.HtmlDecode(value); public static string HtmlUnescape(string value)
=> WebUtility.HtmlDecode(value);
} }
+181 -92
View File
@@ -3,44 +3,171 @@
namespace MeloongCore; namespace MeloongCore;
public static class FileUtils { public static class FileUtils {
#region 写入 #region 读取
/// <summary> /// <summary>
/// 写入文件。 /// 打开指定文件的只读 <see cref="FileStream"/>。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
/// </summary> /// </summary>
public static void Write(string filePath, string text, Encoding? encoding = null) { public static FileStream ReadAsStream(string filePath)
Write(filePath, (encoding ?? new UTF8Encoding()).GetBytes(text)); => ResilientUtils.RetryOn<IOException, FileStream>(()
=> new(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
/// <summary>
/// 读取文件中的所有内容。
/// </summary>
public static byte[] ReadAsBytes(string filePath) {
using Stream fs = FileUtils.ReadAsStream(filePath); // 不能使用 File.ReadAllBytes,它不指定 FileShare.ReadWrite,会在文件被占用时抛出异常
using MemoryStream ms = new();
fs.CopyTo(ms);
return ms.ToArray();
} }
/// <summary> /// <summary>
/// 写入文件。 /// 读取文件中的所有内容。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。
/// </summary> /// </summary>
public static void Write(string filePath, IEnumerable<byte> content) { public static string ReadAsString(string filePath, Encoding? encoding = null)
Write(filePath, [..content]); => FileUtils.ReadAsBytes(filePath).GetString(encoding);
/// <summary>
/// 读取文件中的所有内容。
/// 若文件不存在或读取失败,返回 <see langword="null"/>,而不是抛出异常。
/// </summary>
public static string? TryReadAsString(string filePath, Encoding? encoding = null) {
try {
if (!FileUtils.Exists(filePath)) return null;
return FileUtils.ReadAsBytes(filePath).GetString(encoding);
} catch {
return null;
}
} }
/// <summary> /// <summary>
/// 写入文件。 /// 读取文件中的所有内容,并按行分割。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。 /// </summary>
public static string[] ReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null)
=> FileUtils.ReadAsString(filePath, encoding).SplitLines(skipEmptyLines);
/// <summary>
/// 读取文件中的所有内容,并按行分割。
/// 若文件不存在或读取失败,返回空数组,而不是抛出异常。
/// </summary>
public static string[] TryReadAsLines(string filePath, bool skipEmptyLines = false, Encoding? encoding = null)
=> FileUtils.TryReadAsString(filePath, encoding)?.SplitLines(skipEmptyLines) ?? [];
#endregion
#region 创建 / 写入
/// <summary>
/// 创建文件,并将 <paramref name="text" /> 写入文件。
/// 若文件已存在,则会覆盖原文件。
/// </summary>
public static void Write(string filePath, string text, Encoding? encoding = null)
=> FileUtils.Write(filePath, (encoding ?? new UTF8Encoding()).GetBytes(text));
/// <summary>
/// 创建文件,并将 <paramref name="content" /> 写入文件。
/// 若文件已存在,则会覆盖原文件。
/// </summary>
public static void Write(string filePath, IEnumerable<byte> content)
=> FileUtils.Write(filePath, [.. content]);
/// <summary>
/// 创建文件,并将 <paramref name="content" /> 写入文件。
/// 若文件已存在,则会覆盖原文件。
/// </summary> /// </summary>
public static void Write(string filePath, byte[] content) { public static void Write(string filePath, byte[] content) {
DirectoryUtils.Create(filePath, isFilePath: true); DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
Logger.Trace(() => $"写入文件:{filePath}({content.Length} 字节)"); Logger.Trace($"写入文件:{filePath}({content.Length} 字节)");
File.WriteAllBytes(PathUtils.WithLongPath(filePath), content); ResilientUtils.RetryOn<IOException>(() => {
FileUtils.Delete(filePath);
File.WriteAllBytes(PathUtils.ForApi(filePath), content);
});
} }
/// <summary> /// <summary>
/// 将 <paramref name="stream" /> 写入文件。 /// 创建文件,并将 <paramref name="stream" /> 写入文件。
/// 会将流的位置主动重置到开头。 /// 会将流的位置主动重置到开头。
/// 如果文件或文件夹不存在,则会自动创建。若已存在,则会覆盖原文件。 /// 若文件已存在,则会覆盖原文件。
/// </summary> /// </summary>
public static void Write(string filePath, Stream stream) { public static void Write(string filePath, Stream stream) {
using FileStream fileStream = CreateAsStream(PathUtils.WithLongPath(filePath)); ResilientUtils.RetryOn<IOException>(() => {
FileUtils.Delete(filePath);
using FileStream fileStream = FileUtils.CreateAsStream(filePath);
if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin); if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
Logger.Trace(() => $"写入文件:{filePath}({stream.GetType().Name} {stream.Length} 字节)"); Logger.Trace($"写入文件:{filePath}({stream.GetType().Name}{(stream.CanSeek ? $" {stream.Length} 字节" : "")})");
stream.CopyTo(fileStream); stream.CopyTo(fileStream);
});
}
/// <summary>
/// 创建文件,并打开 <see cref="FileStream"/>。
/// 若文件已存在,则会覆盖原文件。
/// </summary>
public static FileStream CreateAsStream(string filePath) {
DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
Logger.Trace($"创建文件流:{filePath}");
return ResilientUtils.RetryOn<IOException, FileStream>(() => {
FileUtils.Delete(filePath);
return new FileStream(PathUtils.ForApi(filePath), FileMode.Create);
});
}
/// <summary>
/// 在临时文件夹下创建一个随机名称的文件,并返回其路径。
/// </summary>
public static string CreateRandom()
=> ResilientUtils.RetryOn<IOException, string>(Path.GetTempFileName);
#endregion
#region 复制 / 剪切
/// <summary>
/// 复制文件。
/// 会创建对应文件夹、覆盖已有的文件。
/// 若复制自身到自身,则不执行操作;若仅大小写不同,则重命名此文件。
/// </summary>
public static void Copy(string sourceFilePath, string destFilePath) {
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
destFilePath = PathUtils.ForCompare(destFilePath);
if (string.Compare(sourceFilePath, destFilePath, ignoreCase:false) == 0) {
// 复制自身到自身,则不执行操作
Logger.Trace($"复制文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
} else if (string.Compare(sourceFilePath, destFilePath, ignoreCase:true) == 0) {
// 路径仅大小写不同,等效于重命名
Logger.Trace($"复制文件到自身,但大小写不同,等效于重命名文件:{sourceFilePath} → {destFilePath}");
FileUtils.Move(sourceFilePath, destFilePath);
} else {
// 实际的复制
DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
Logger.Trace($"复制文件:{sourceFilePath} → {destFilePath}");
ResilientUtils.RetryOn<IOException>(()
=> File.Copy(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(destFilePath), true));
}
}
/// <summary>
/// 剪切文件。
/// 会创建对应文件夹、覆盖已有的文件。
/// </summary>
public static void Move(string sourceFilePath, string destFilePath) {
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
destFilePath = PathUtils.ForCompare(destFilePath);
if (string.Compare(sourceFilePath, destFilePath, ignoreCase: false) == 0) {
// 剪切自身到自身,则不执行操作
Logger.Trace($"剪切文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
} else if (string.Compare(sourceFilePath, destFilePath, ignoreCase: true) == 0) {
// 路径仅大小写不同
Logger.Trace($"剪切文件到自身,但大小写不同:{sourceFilePath} → {destFilePath}");
ResilientUtils.RetryOn<IOException>(() => {
var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFilePath), Path.GetRandomFileName());
File.Move(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(temp));
File.Move(PathUtils.ForApi(temp), PathUtils.ForApi(destFilePath));
});
} else {
// 实际的剪切
DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
FileUtils.Delete(destFilePath);
Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}");
ResilientUtils.RetryOn<IOException>(()
=> File.Move(PathUtils.ForApi(sourceFilePath), PathUtils.ForApi(destFilePath)));
}
} }
#endregion #endregion
@@ -51,12 +178,13 @@ public static class FileUtils {
/// 删除文件。 /// 删除文件。
/// </summary> /// </summary>
public static void Delete(string filePath, bool toRecycleBin = false) { public static void Delete(string filePath, bool toRecycleBin = false) {
if (!Exists(filePath)) return; if (!FileUtils.Exists(filePath)) return;
Logger.Trace($"{(toRecycleBin ? "将文件删除到回收站" : "删除文件")}:{filePath}"); Logger.Trace($"{(toRecycleBin ? "将文件删除到回收站" : "删除文件")}:{filePath}");
if (toRecycleBin) { if (toRecycleBin) {
DeleteToRecycleBin(filePath); DeleteToRecycleBin(filePath);
} else { } else {
File.Delete(PathUtils.WithLongPath(filePath)); ResilientUtils.RetryOn<IOException>(()
=> File.Delete(PathUtils.ForApi(filePath)));
} }
} }
@@ -65,12 +193,12 @@ public static class FileUtils {
/// </summary> /// </summary>
internal static void DeleteToRecycleBin(string target) { internal static void DeleteToRecycleBin(string target) {
// 实际的删除方法 // 实际的删除方法
static void Run(string filePath) { void Run() {
IShellItem? item = null; IShellItem? item = null;
IFileOperation? op = null; IFileOperation? op = null;
try { try {
var iid = typeof(IShellItem).GUID; var iid = typeof(IShellItem).GUID;
Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(PathUtils.WithoutLongPath(filePath), IntPtr.Zero, ref iid, out item)); Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(PathUtils.RemoveExtendedPrefix(target), IntPtr.Zero, ref iid, out item));
op = (IFileOperation) new FileOperation(); op = (IFileOperation) new FileOperation();
op.SetOperationFlags(0x0040 | 0x0010 | 0x0004); // FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT op.SetOperationFlags(0x0040 | 0x0010 | 0x0004); // FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT
op.DeleteItem(item, IntPtr.Zero); op.DeleteItem(item, IntPtr.Zero);
@@ -84,17 +212,23 @@ public static class FileUtils {
} }
// 在 STA 线程中执行删除方法 // 在 STA 线程中执行删除方法
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) { if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) {
Run(target); ResilientUtils.RetryOn<IOException>(Run);
} else { } else {
System.Runtime.ExceptionServices.ExceptionDispatchInfo? internalEx = null; // 捕获内部异常 System.Runtime.ExceptionServices.ExceptionDispatchInfo? internalEx = null; // 捕获内部异常
var thread = new Thread(() => { try { Run(target); } catch (Exception ex) { internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex); } }); var thread = new Thread(() => {
try {
ResilientUtils.RetryOn<IOException>(Run);
} catch (Exception ex) {
internalEx = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex);
}
}) { IsBackground = true, Name = nameof(DeleteToRecycleBin) };
thread.SetApartmentState(ApartmentState.STA); thread.SetApartmentState(ApartmentState.STA);
thread.Start(); thread.Start();
thread.Join(); thread.Join();
internalEx?.Throw(); internalEx?.Throw();
} }
} }
// 用于删除到回收站的接口 // API
[DllImport("shell32.dll", CharSet = CharSet.Unicode)] [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv); static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
@@ -127,27 +261,7 @@ public static class FileUtils {
#endregion #endregion
#region FileStream #region 压缩 / 解压
/// <summary>
/// 打开该文件的只读 <see cref="FileStream"/>。
/// </summary>
public static FileStream ReadAsStream(string filePath) {
return new(PathUtils.WithLongPath(filePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
/// <summary>
/// 在指定路径创建文件,并打开 <see cref="FileStream"/>。
/// </summary>
public static FileStream CreateAsStream(string filePath) {
DirectoryUtils.Create(filePath, isFilePath: true);
Logger.Trace($"创建文件流:{filePath}");
return new(PathUtils.WithLongPath(filePath), FileMode.Create);
}
#endregion
#region 压缩包
/// <summary> /// <summary>
/// 以只读模式打开压缩文件。 /// 以只读模式打开压缩文件。
@@ -155,8 +269,8 @@ public static class FileUtils {
/// </summary> /// </summary>
public static ZipArchive OpenZip(string zipFilePath) { public static ZipArchive OpenZip(string zipFilePath) {
ZipArchive TryOpen(Encoding encoding) { ZipArchive TryOpen(Encoding encoding) {
Logger.Trace(() => $"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}"); Logger.Trace($"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}");
var result = ZipFile.Open(PathUtils.WithLongPath(zipFilePath), ZipArchiveMode.Read, encoding); var result = ZipFile.Open(PathUtils.ForApi(zipFilePath), ZipArchiveMode.Read, encoding);
try { try {
_ = result.Entries; // 如果编码有误,会在这里抛出 DecoderFallbackException;如果文件异常,会在这里抛出 InvalidDataException _ = result.Entries; // 如果编码有误,会在这里抛出 DecoderFallbackException;如果文件异常,会在这里抛出 InvalidDataException
return result; return result;
@@ -182,11 +296,11 @@ public static class FileUtils {
/// </summary> /// </summary>
/// <param name="progressHandler">参数为已完成的总比例(0~1)。</param> /// <param name="progressHandler">参数为已完成的总比例(0~1)。</param>
public static void ExtractToDirectory(string compressionFile, string outputDirectory, Action<double>? progressHandler = null) { public static void ExtractToDirectory(string compressionFile, string outputDirectory, Action<double>? progressHandler = null) {
compressionFile = PathUtils.WithLongPath(compressionFile); compressionFile = PathUtils.ForApi(compressionFile);
DirectoryUtils.Create(outputDirectory); DirectoryUtils.Create(outputDirectory);
// 解压 gz(gz 不需要考虑编码) // 解压 gz(gz 不需要考虑编码)
if (compressionFile.EndsWithF(".gz", true)) { if (compressionFile.EndsWithF(".gz", true)) {
string outFilePath = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(compressionFile)); string outFilePath = Path.Combine(outputDirectory, PathUtils.GetFileNameWithoutExtension(compressionFile));
Logger.Trace($"解压 gz 文件:{compressionFile} → {outFilePath}"); Logger.Trace($"解压 gz 文件:{compressionFile} → {outFilePath}");
using var fileStream = FileUtils.ReadAsStream(compressionFile); using var fileStream = FileUtils.ReadAsStream(compressionFile);
using var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress); using var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress);
@@ -204,8 +318,8 @@ public static class FileUtils {
if (totalCount > 0) progressHandler?.Invoke((double) doneCount / totalCount); if (totalCount > 0) progressHandler?.Invoke((double) doneCount / totalCount);
if (string.IsNullOrEmpty(entry.Name)) continue; // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空) if (string.IsNullOrEmpty(entry.Name)) continue; // 跳过文件夹条目(ZipArchive 会将文件夹也作为一个 entry,但它们的 Name 为空)
// ZipSlip 修复 // ZipSlip 修复
string outputFilePath = PathUtils.WithLongPath(Path.GetFullPath(Path.Combine(outputDirectory, entry.FullName))); string outputFilePath = PathUtils.ForCompare(Path.Combine(outputDirectory, entry.FullName));
if (!outputFilePath.StartsWithF(PathUtils.WithSeparator(PathUtils.WithLongPath(Path.GetFullPath(outputDirectory))), ignoreCase:true)) if (!outputFilePath.StartsWithF(PathUtils.AddSlashSuffix(PathUtils.ForCompare(outputDirectory)), ignoreCase:true))
throw new ZipSlipException($"Zip 文件项 {entry.FullName} 的路径在压缩包之外,这可能导致安全问题"); throw new ZipSlipException($"Zip 文件项 {entry.FullName} 的路径在压缩包之外,这可能导致安全问题");
// 实际的解压 // 实际的解压
using var entryStream = entry.Open(); using var entryStream = entry.Open();
@@ -219,12 +333,11 @@ public static class FileUtils {
/// 会自动创建文件夹。会覆盖已有文件。 /// 会自动创建文件夹。会覆盖已有文件。
/// </summary> /// </summary>
public static void CreateZipFromDirectory(string outputFullPath, string sourceDirectory) { public static void CreateZipFromDirectory(string outputFullPath, string sourceDirectory) {
outputFullPath = PathUtils.WithLongPath(outputFullPath); DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
sourceDirectory = PathUtils.WithLongPath(sourceDirectory);
DirectoryUtils.Create(outputFullPath, isFilePath: true);
FileUtils.Delete(outputFullPath); FileUtils.Delete(outputFullPath);
Logger.Trace($"将文件夹中的内容压缩为 zip 文件:{sourceDirectory} → {outputFullPath}"); Logger.Trace($"将文件夹中的内容压缩为 zip 文件:{sourceDirectory} → {outputFullPath}");
ZipFile.CreateFromDirectory(sourceDirectory, outputFullPath); ResilientUtils.RetryOn<IOException>(()
=> ZipFile.CreateFromDirectory(PathUtils.ForApi(sourceDirectory), PathUtils.ForApi(outputFullPath)));
} }
/// <summary> /// <summary>
@@ -234,11 +347,11 @@ public static class FileUtils {
public static void CreateZipFromFiles(string outputFullPath, params string[] sourceFiles) { public static void CreateZipFromFiles(string outputFullPath, params string[] sourceFiles) {
var sources = new Dictionary<string, string>(); var sources = new Dictionary<string, string>();
foreach (var source in sourceFiles) { foreach (var source in sourceFiles) {
string fileName = Path.GetFileName(source); string fileName = PathUtils.GetLastPart(source);
if (sources.ContainsKey(fileName)) throw new ArgumentException($"尝试将多个同文件名的文件放进压缩包中({fileName})", nameof(sourceFiles)); if (sources.ContainsKey(fileName)) throw new ArgumentException($"尝试将多个同文件名的文件放进压缩包中({fileName})", nameof(sourceFiles));
sources.Add(fileName, source); sources.Add(fileName, source);
} }
CreateZipFromFiles(outputFullPath, sources); FileUtils.CreateZipFromFiles(outputFullPath, sources);
} }
/// <summary> /// <summary>
@@ -247,12 +360,12 @@ public static class FileUtils {
/// </summary> /// </summary>
/// <param name="sources">键为 zip 文件下的路径,值为文件的本地路径。</param> /// <param name="sources">键为 zip 文件下的路径,值为文件的本地路径。</param>
public static void CreateZipFromFiles(string outputFullPath, IDictionary<string, string> sources) { public static void CreateZipFromFiles(string outputFullPath, IDictionary<string, string> sources) {
outputFullPath = PathUtils.WithLongPath(outputFullPath); DirectoryUtils.Create(PathUtils.RemoveLastPart(outputFullPath));
DirectoryUtils.Create(outputFullPath, isFilePath: true);
FileUtils.Delete(outputFullPath); FileUtils.Delete(outputFullPath);
using var archive = ZipFile.Open(outputFullPath, ZipArchiveMode.Create); using var archive = ResilientUtils.RetryOn<IOException, ZipArchive>(()
Logger.Trace(() => $"创建 zip 文件:{sources.Count} 个文件 → {outputFullPath}\n{sources.Select(p => $"- {p.Value} → {p.Key}").Join('\n')}"); => ZipFile.Open(PathUtils.ForApi(outputFullPath), ZipArchiveMode.Create));
foreach (var pair in sources) archive.CreateEntryFromFile(PathUtils.WithLongPath(pair.Value), pair.Key.Replace('\\', '/'), CompressionLevel.Optimal); Logger.Trace($"创建 zip 文件:{sources.Count} 个文件 → {outputFullPath}\n{sources.Select(p => $"- {p.Value} → {p.Key}").Join('\n')}");
foreach (var pair in sources) archive.CreateEntryFromFile(PathUtils.ForApi(pair.Value), pair.Key.Replace('\\', '/'), CompressionLevel.Optimal);
} }
#endregion #endregion
@@ -260,37 +373,13 @@ public static class FileUtils {
/// <summary> /// <summary>
/// 确定指定的文件是否存在。 /// 确定指定的文件是否存在。
/// </summary> /// </summary>
public static bool Exists(string filePath) { public static bool Exists(string filePath)
return File.Exists(PathUtils.WithLongPath(filePath)); => File.Exists(PathUtils.ForApi(filePath));
}
/// <summary> /// <summary>
/// 创建 <see cref="FileInfo"/> 对象。 /// 获取 <see cref="FileInfo"/> 对象。
/// </summary> /// </summary>
public static FileInfo GetInfo(string path) { public static FileInfo GetInfo(string path)
return new(PathUtils.WithLongPath(path)); => new(PathUtils.ForApi(path));
}
/// <summary>
/// 复制文件。
/// 会创建对应文件夹、覆盖已有的文件。
/// </summary>
public static void Copy(string sourceFilePath, string destFilePath) {
if (sourceFilePath == destFilePath) return; // 如果复制同一个文件则跳过
DirectoryUtils.Create(destFilePath, isFilePath: true);
Logger.Trace($"复制文件:{sourceFilePath} → {destFilePath}");
File.Copy(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath), true);
}
/// <summary>
/// 剪切文件。
/// 会创建对应文件夹、覆盖已有的文件。
/// </summary>
public static void Move(string sourceFilePath, string destFilePath) {
if (sourceFilePath == destFilePath) return; // 如果移动同一个文件则跳过
DirectoryUtils.Create(destFilePath, isFilePath: true);
Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}");
File.Move(PathUtils.WithLongPath(sourceFilePath), PathUtils.WithLongPath(destFilePath));
}
} }
+23
View File
@@ -0,0 +1,23 @@
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();
}
}
+2 -6
View File
@@ -7,13 +7,9 @@ public class HttpRequestCodeException(string message, HttpStatusCode statusCode,
/// <summary> /// <summary>
/// HTTP 请求的状态码。 /// HTTP 请求的状态码。
/// </summary> /// </summary>
public HttpStatusCode StatusCode = statusCode; public HttpStatusCode StatusCode { get; } = statusCode;
/// <summary> /// <summary>
/// 远程服务器给予的回复。 /// 远程服务器给予的回复。
/// </summary> /// </summary>
public string? Response { get; set; } = response; public string? Response { get; } = response;
}
public static class HttpUtils {
} }
+12 -6
View File
@@ -30,17 +30,21 @@ public static class MathUtils {
/// 转换为 2 到 86 进制的字符串。 /// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。 /// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary> /// </summary>
public static string ConvertRadix(this long input, int toRadix) => ConvertRadix((BigInteger) input, toRadix); public static string ConvertRadix(this long input, int toRadix)
=> ConvertRadix((BigInteger) input, toRadix);
/// <summary> /// <summary>
/// 转换为 2 到 86 进制的字符串。 /// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。 /// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary> /// </summary>
public static string ConvertRadix(this int input, int toRadix) => ConvertRadix((BigInteger) input, toRadix); public static string ConvertRadix(this int input, int toRadix)
=> ConvertRadix((BigInteger) input, toRadix);
/// <summary> /// <summary>
/// 转换为 2 到 86 进制的字符串。 /// 转换为 2 到 86 进制的字符串。
/// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。 /// 进制参考:含大写字母 36,含大小写字母 62,含大小写字母和特殊符号 86。
/// </summary> /// </summary>
public static string ConvertRadix(this byte input, int toRadix) => ConvertRadix((BigInteger) input, toRadix); public static string ConvertRadix(this byte input, int toRadix)
=> ConvertRadix((BigInteger) input, toRadix);
private static string ConvertRadix(this BigInteger input, int toRadix) { private static string ConvertRadix(this BigInteger input, int toRadix) {
const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',"; const string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+=!?@#$%^&*()[]{}<>;:',";
if (toRadix < 2 || toRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(toRadix), $"{nameof(toRadix)} must be between 2 and 86."); if (toRadix < 2 || toRadix > digits.Length) throw new ArgumentOutOfRangeException(nameof(toRadix), $"{nameof(toRadix)} must be between 2 and 86.");
@@ -76,8 +80,8 @@ public static class MathUtils {
/// 在一个范围中进行线性插值。 /// 在一个范围中进行线性插值。
/// 返回值将被舍入到小数点后 7 位,以解决浮点数误差问题。 /// 返回值将被舍入到小数点后 7 位,以解决浮点数误差问题。
/// </summary> /// </summary>
public static double Lerp(double start, double end, double percentage) => public static double Lerp(double start, double end, double percentage)
Math.Round(start + (end - start) * percentage, 7); => Math.Round(start + (end - start) * percentage, 7);
/// <summary> /// <summary>
/// 计算二阶贝塞尔曲线。 /// 计算二阶贝塞尔曲线。
@@ -87,10 +91,12 @@ public static class MathUtils {
if (t > 0.9999999) return 1; if (t > 0.9999999) return 1;
double a = t; double a = t;
double b; double b;
int maxIterations = 1000;
do { do {
b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1); b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1);
a += (t - b) * 0.5; a += (t - b) * 0.5;
} while (!(Math.Abs(b - t) < accuracy)); // 精度 maxIterations--;
} while (!(Math.Abs(b - t) < accuracy) && maxIterations > 0);
return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1); return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1);
} }
+125 -25
View File
@@ -4,18 +4,16 @@ public static class PathUtils {
#region 分隔符 #region 分隔符
/// <summary> /// <summary>
/// 确保路径的结尾包含文件夹分隔符。 /// 确保路径的末尾包含任意文件夹分隔符。
/// </summary> /// </summary>
public static string WithSeparator(string folder) { public static string AddSlashSuffix(string folder)
return folder.EndsWithF(Path.DirectorySeparatorChar) ? folder : folder + Path.DirectorySeparatorChar; => folder + (folder.EndsWithF(Path.DirectorySeparatorChar) || folder.EndsWithF(Path.AltDirectorySeparatorChar) ? "" : Path.DirectorySeparatorChar);
}
/// <summary> /// <summary>
/// 确保路径的结尾不包含文件夹分隔符。 /// 确保路径的结尾不包含文件夹分隔符。
/// </summary> /// </summary>
public static string WithoutSeparator(string folder) { public static string RemoveSlashSuffix(string folder)
return folder.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); => folder.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
#endregion #endregion
@@ -23,49 +21,47 @@ public static class PathUtils {
/// <summary> /// <summary>
/// 若路径较长,则尽量将其转换为短路径。 /// 若路径较长,则尽量将其转换为短路径。
/// 若输入的是文件夹路径,不保证其结尾是否有文件夹分隔符。 /// <para/>结果的开头不含 <c>\\?\</c>,结尾不含分隔符。
/// </summary> /// </summary>
public static string ToShortPath(string fullName, bool keepFileName = false) { public static string ToShortPath(string fullName, bool keepFileName = false) {
if (string.IsNullOrEmpty(fullName)) return fullName; if (string.IsNullOrEmpty(fullName)) return fullName;
fullName = PathUtils.WithoutLongPath( fullName.Replace('/', '\\')); if (!fullName.Contains(@":\")) return fullName;
if (fullName.Length <= 200) return fullName; if (fullName.Length <= 200) return fullName;
fullName = PathUtils.ForCompare(fullName);
// 保留文件名 // 保留文件名
string pathToKeep = ""; string pathToKeep = "";
string pathToShorten = fullName; string pathToShorten = fullName;
if (fullName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名 if (fullName.EndsWithF(".jar", true)) keepFileName = true; // jar 文件的文件名需要保留原样,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
if (keepFileName && FileUtils.Exists(fullName)) { if (keepFileName && FileUtils.Exists(fullName)) {
pathToKeep = Path.GetFileName(fullName); pathToKeep = PathUtils.GetLastPart(fullName);
pathToShorten = Path.GetDirectoryName(fullName); pathToShorten = PathUtils.RemoveLastPart(fullName);
} }
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短 // 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在 while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在
string parentPath = Path.GetDirectoryName(pathToShorten); string parentPath = Path.GetDirectoryName(pathToShorten);
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return fullName; // 已经到达根目录,全都不存在,直接返回 if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return fullName; // 已经到达根目录,全都不存在,直接返回
pathToKeep = Path.Combine(Path.GetFileName(pathToShorten), pathToKeep); pathToKeep = Path.Combine(PathUtils.GetLastPart(pathToShorten), pathToKeep);
pathToShorten = parentPath; pathToShorten = parentPath;
} }
if (pathToShorten.Length <= 10) return fullName; if (pathToShorten.Length <= 10) return fullName;
// 实际缩短路径
// 缩短路径
char[] buffer = new char[260]; char[] buffer = new char[260];
int result = GetShortPathNameW(pathToShorten, buffer, buffer.Length); int result = GetShortPathNameW(PathUtils.ForApi(pathToShorten), buffer, buffer.Length);
if (result == 0) return fullName; if (result == 0) return fullName;
string shortPath = new(buffer, 0, result); string shortPath = new(buffer, 0, result);
return Path.Combine(shortPath, pathToKeep); return PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.Combine(shortPath, pathToKeep)));
} }
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern int GetShortPathNameW(string lpszLongPath, [Out] char[] buffer, int cchBuffer); private static extern int GetShortPathNameW(string lpszLongPath, [Out] char[] buffer, int cchBuffer);
/// <summary> /// <summary>
/// 将完整路径转换为以 \\?\ 开头的标准长路径格式。 /// 将完整路径转换为以 <c>\\?\</c> 开头的扩展格式。
/// 这会去除路径末尾的分隔符,且将 / 替换为 \。 /// 这会去除路径末尾的分隔符,将 / 替换为 \。
/// </summary> /// </summary>
public static string WithLongPath(string path) { public static string ToExtendedFormat(string path) {
if (string.IsNullOrWhiteSpace(path)) return path; if (string.IsNullOrWhiteSpace(path)) return path;
if (path.StartsWithF(@"\\?\")) return path; // 已经是长路径 if (path.StartsWithF(@"\\?\")) return path; // 已经是长路径
path = WithoutSeparator(path).Replace('/', '\\'); // API 要求这个格式…… path = RemoveSlashSuffix(path).Replace('/', '\\'); // API 要求这个格式……
if (path.StartsWithF(@"\\")) { if (path.StartsWithF(@"\\")) {
return $@"\\?\UNC\{path.Substring(2)}"; return $@"\\?\UNC\{path.Substring(2)}";
} else { } else {
@@ -74,10 +70,114 @@ public static class PathUtils {
} }
/// <summary> /// <summary>
/// 去除路径开头的 \\?\。 /// 去除路径开头的 <c>\\?\</c>。
/// </summary> /// </summary>
public static string WithoutLongPath(string path) => public static string RemoveExtendedPrefix(string path) {
path.AfterLast(@"\\?\"); if (path.StartsWithF(@"\\?\UNC\")) return @"\\" + path.AfterLast(@"\\?\UNC\");
if (path.StartsWithF(@"\\?\")) return path.AfterLast(@"\\?\");
return path;
}
#endregion
#region 路径处理
/// <summary>
/// 去除路径的最后一级,并移除末尾的分隔符。
/// <code>
/// "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"
/// </code></summary>
public static string RemoveLastPart(string path) {
if (path!.Contains("://")) { // 网络路径
path = PathUtils.RemoveSlashSuffix(path.BeforeFirst("#").BeforeFirst("?")); // 去除参数
}
return PathUtils.RemoveSlashSuffix(path!).BeforeLastOfAny([@"\", "/"]);
}
/// <summary>
/// 获取路径的最后一级,即文件名,或当前文件夹名。
/// <code>
/// "C:\foo\bar.txt" → "bar.txt"
/// "C:\foo\bar\" → "bar"
/// "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("?")); // 去除参数
} else { // 文件路径
path = PathUtils.RemoveSlashSuffix(path);
}
return path.AfterLastOfAny([@"\", "/"]);
}
/// <summary>
/// 获取路径或文件名中,仅不包含最后一级扩展名的部分。
/// <code>
/// "C:\foo\bar.txt" → "bar"
/// "create.jar.disabled" → "create.jar"
/// "https://foo.bar/file/page.xaml.vb?arg=1" → "page.xaml"
/// </code>
/// </summary>
public static string GetFileNameWithoutExtension(string path)
=> GetLastPart(path).BeforeLast(".");
/// <summary>
/// 获取路径或文件名中的最后一级文件扩展名,不包含 <c>.</c>,固定小写。
/// 如果没有 <c>.</c> 则返回空字符串。
/// <code>
/// "C:\FOO\BAR.TXT" → "txt"
/// "create.jar.disabled" → "disabled"
/// "C:\foo\bar" → ""
/// "https://foo.bar/file/page.xaml.vb?arg=1" → "vb"
/// </code>
/// </summary>
public static string GetExtension(string path) {
var name = GetLastPart(path);
return name.Contains(".") ? name.AfterLast(".").Lower() : "";
}
/// <summary>
/// 获取路径的盘符,返回一个大写字母。
/// 若路径不包含盘符,则返回 <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]);
}
/// <summary>
/// 统一路径格式,以便比较。
/// <para/>具体而言:将短路径展开,去除前导的 <c>\\?\</c>,将分隔符改为 \,去除末尾的分隔符。
/// </summary>
public static string ForCompare(string path)
=> PathUtils.RemoveSlashSuffix(PathUtils.RemoveExtendedPrefix(Path.GetFullPath(path)).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);
}
#endregion
#region 常用路径
/// <summary>
/// 程序可执行文件的所在文件夹,以 \ 结尾。
/// </summary>
public static string CurrentFolder => PathUtils.AddSlashSuffix(AppDomain.CurrentDomain.BaseDirectory);
#endregion #endregion
+41
View File
@@ -0,0 +1,41 @@
namespace MeloongCore;
public static class ResilientUtils {
/// <summary>
/// 在抛出任意异常时,延迟并自动重试。
/// </summary>
public static void Retry(Action action, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "")
=> RetryOn<Exception>(action, maxAttempts, delayMs, caller);
/// <summary>
/// 在抛出特定异常时,延迟并自动重试。
/// </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 Retry<TOut>(Func<TOut> func, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "")
=> RetryOn<Exception, TOut>(func, maxAttempts, delayMs, caller);
/// <summary>
/// 在抛出特定异常时,延迟并自动重试。
/// </summary>
public static TOut RetryOn<TException, TOut>(Func<TOut> func, int maxAttempts = 2, int delayMs = 200, [CallerMemberName] string caller = "") where TException : Exception {
int attempt = 0;
while (true) {
try {
return func(); // 成功则退出
} catch (TException ex) {
attempt++;
if (attempt < maxAttempts) {
Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,将在 {delayMs}ms 后重试");
Thread.Sleep(delayMs);
} else { // 超过最大尝试次数
Logger.Warn(ex, $"第 {attempt} 次 {caller} 尝试失败,已到达最大尝试次数");
throw;
}
}
}
}
}
+2 -8
View File
@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net48</TargetFramework> <TargetFramework>net48</TargetFramework>
<OutputType>Library</OutputType> <OutputType>Exe</OutputType>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks> <AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
@@ -23,13 +23,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="System.IO.Compression" Version="4.3.0" /> <PackageReference Include="System.IO.Compression" Version="4.3.0" />
<PackageReference Include="xunit" Version="2.9.3" /> <PackageReference Include="TUnit" Version="1.43.38" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="PolySharp" Version="1.15.0"> <PackageReference Include="PolySharp" Version="1.15.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -71,7 +66,6 @@
<Using Include="MeloongCore" /> <Using Include="MeloongCore" />
<Using Include="MeloongCore.Extensions" /> <Using Include="MeloongCore.Extensions" />
<Using Include="MeloongCore.Tests" /> <Using Include="MeloongCore.Tests" />
<Using Include="Xunit" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
+21 -5
View File
@@ -1,23 +1,39 @@
namespace MeloongCore.Tests; namespace MeloongCore.Tests;
/// <summary>
/// 所有测试的基类。
/// 会初始化 MeloongCore 并重定向日志输出。
/// </summary>
public abstract class TestBase {
public TestBase() {
MeloongCore.Main.Init(new TestLogger());
}
private class TestLogger : BaseLogger {
public override void HandleBehavior(string? rawMessage, string formattedMessage, LogBehavior behavior, Exception? ex)
=> TestContext.Current!.OutputWriter.WriteLine(formattedMessage);
}
}
/// <summary> /// <summary>
/// 用于带文件测试的基类。 /// 用于带文件测试的基类。
/// 会在极端路径下创建测试用的临时文件夹。 /// 会在极端路径下创建测试用的临时文件夹。
/// </summary> /// </summary>
public abstract class TestWithFolder { public abstract class TestWithFolder : TestBase {
/// <summary> /// <summary>
/// 测试用的临时文件夹路径。 /// 测试用的临时文件夹路径。
/// 这是一个包含特殊字符的长路径,不以 \\?\ 开头,以 \ 结尾。 /// 这是一个包含特殊字符的长路径,不以 \\?\ 开头,以 \ 结尾。
/// </summary> /// </summary>
public readonly string tempFolder; public readonly string tempFolder;
public TestWithFolder() { public TestWithFolder() : base() {
tempFolder = Path.Combine( tempFolder = Path.Combine(
Path.GetTempPath(), "PCL", "Tests", Path.GetTempPath(), "PCL", "Tests",
$"{GetType().Name}-{Guid.NewGuid()}", $"{GetType().Name}-{Guid.NewGuid()}",
"文件夹 Dir_!@#$%^&()_+={}[];',_", "文件夹 Dir_!@#$%^&()_+={}[];',_",
new string('X', 200), new string('X', 200)) + @"\"; new string('X', 200), new string('X', 200)) + @"\";
Directory.CreateDirectory(@"\\?\" + tempFolder); DirectoryUtils.Create(tempFolder);
} }
/// <summary> /// <summary>
@@ -25,8 +41,8 @@ public abstract class TestWithFolder {
/// </summary> /// </summary>
public string GetTestFile(string fileName) { public string GetTestFile(string fileName) {
var sourceFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", GetType().Name.Replace("Test", ""), fileName); var sourceFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", GetType().Name.Replace("Test", ""), fileName);
var distPath = Path.Combine(tempFolder, Path.GetFileName(sourceFilePath)); var distPath = Path.Combine(tempFolder, PathUtils.GetLastPart(sourceFilePath));
File.Copy(sourceFilePath, @"\\?\" + distPath); FileUtils.Copy(sourceFilePath, distPath);
return distPath; return distPath;
} }
+80
View File
@@ -0,0 +1,80 @@
namespace MeloongCore.Tests;
public class DirectoryUtilsTest : TestWithFolder {
#region 剪切、复制
[Test]
[Arguments("Source", "目标文件夹")]
[Arguments("Source", "Source")]
[Arguments("Source", "soURCE")]
public async Task 复制(string sourceName, string destName) {
var src = Path.Combine(tempFolder, sourceName);
DirectoryUtils.Create(Path.Combine(src, "sub"));
FileUtils.Write(Path.Combine(src, "a.txt"), "aaa");
FileUtils.Write(Path.Combine(src, "sub", "b file.txt"), "bbb");
var dest = Path.Combine(tempFolder, destName);
DirectoryUtils.Copy(src, dest);
await Assert.That(FileUtils.ReadAsString(Path.Combine(src, "a.txt"))).IsEqualTo("aaa");
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "a.txt"))).IsEqualTo("aaa");
await Assert.That(FileUtils.ReadAsString(Path.Combine(src, "sub", "b file.txt"))).IsEqualTo("bbb");
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "sub", "b file.txt"))).IsEqualTo("bbb");
await Assert.That(DirectoryUtils.GetDirectories(Path.Combine(tempFolder))).Contains(dest); // 目标文件夹名
}
[Test]
[Arguments("Source", "目标文件夹")]
[Arguments("Source", "Source")]
[Arguments("Source", "soURCE")]
public async Task 剪切(string sourceName, string destName) {
var src = Path.Combine(tempFolder, sourceName);
DirectoryUtils.Create(Path.Combine(src, "sub"));
FileUtils.Write(Path.Combine(src, "a.txt"), "aaa");
FileUtils.Write(Path.Combine(src, "sub", "b file.txt"), "bbb");
var dest = Path.Combine(tempFolder, destName);
DirectoryUtils.Move(src, dest);
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "a.txt"))).IsEqualTo("aaa");
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "sub", "b file.txt"))).IsEqualTo("bbb");
if (src != dest) await Assert.That(DirectoryUtils.GetDirectories(Path.Combine(tempFolder))).DoesNotContain(src);
await Assert.That(DirectoryUtils.GetDirectories(Path.Combine(tempFolder))).Contains(dest); // 目标文件夹名
}
[Test]
public async Task 剪切_不同磁盘() {
// 寻找两个磁盘
var drives = DriveInfo.GetDrives()
.Where(d => d.IsReady && d.DriveType == DriveType.Fixed)
.ToArray();
if (drives.Length < 2) return;
var id = Guid.NewGuid().ToString("N");
var srcRoot = Path.Combine(drives[0].RootDirectory.FullName, "Temp", $"MeloongTest_{id}");
var destRoot = Path.Combine(drives[1].RootDirectory.FullName, "Temp", $"MeloongTest_{id}");
var src = Path.Combine(srcRoot, "src");
var dest = Path.Combine(destRoot, "dest");
try {
DirectoryUtils.Create(src);
FileUtils.Write(Path.Combine(src, "a.txt"), "aaa");
FileUtils.Write(Path.Combine(src, "sub", "b file.txt"), "bbb");
DirectoryUtils.Move(src, dest);
await Assert.That(DirectoryUtils.Exists(src)).IsFalse();
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "a.txt"))).IsEqualTo("aaa");
await Assert.That(FileUtils.ReadAsString(Path.Combine(dest, "sub", "b file.txt"))).IsEqualTo("bbb");
} finally {
DirectoryUtils.Delete(srcRoot);
DirectoryUtils.Delete(destRoot);
}
}
[Test]
public void 剪切_安全检查()
=> Assert.Throws<UnauthorizedAccessException>(() => DirectoryUtils.Move(PathUtils.CurrentFolder, Path.Combine(tempFolder, "SafetyCheckDest")));
#endregion
}
+25 -27
View File
@@ -1,45 +1,43 @@
namespace MeloongCore.Tests; namespace MeloongCore.Tests;
public class FileUtilsTest : TestWithFolder { public class FileUtilsTest : TestWithFolder {
#region 压缩包 #region 解压
[Theory] [Test]
[InlineData("GB Encoding.zip")] [Arguments("GB Encoding.zip")]
[InlineData("UTF8 Encoding.zip")] [Arguments("UTF8 Encoding.zip")]
public void Compression_ReadZip(string testFile) { public async Task 解压_ReadZip(string testFile) {
double progress = 0; double progress = 0;
string output = Path.Combine(tempFolder, "Extracted"); string output = Path.Combine(tempFolder, "Extracted");
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p); FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p);
Assert.Equal(1, progress); await Assert.That(progress).IsEqualTo(1);
Assert.True(DirectoryUtils.Exists(Path.Combine(output, "文件夹"))); await Assert.That(DirectoryUtils.Exists(Path.Combine(output, "文件夹"))).IsTrue();
Assert.False(DirectoryUtils.Exists(Path.Combine(output, "空文件夹"))); await Assert.That(DirectoryUtils.Exists(Path.Combine(output, "空文件夹"))).IsFalse();
Assert.Contains("FabricLoader", File.ReadAllText(PathUtils.WithLongPath(Path.Combine(output, "fabricloader.log")))); await Assert.That(File.ReadAllText(PathUtils.ToExtendedFormat(Path.Combine(output, "fabricloader.log")))).Contains("FabricLoader");
Assert.Contains("测试内容", File.ReadAllText(PathUtils.WithLongPath(Path.Combine(output, "文件夹", "中文文件.txt")))); await Assert.That(File.ReadAllText(PathUtils.ToExtendedFormat(Path.Combine(output, "文件夹", "中文文件.txt")))).Contains("测试内容");
} }
[Theory] [Test]
[InlineData("GZ.gz", "LTCat")] [Arguments("GZ.gz", "LTCat")]
public void Compression_ReadGz(string testFile, string containsText) { public async Task 解压_ReadGz(string testFile, string containsText) {
double progress = 0; double progress = 0;
string output = Path.Combine(tempFolder, "Extracted"); string output = Path.Combine(tempFolder, "Extracted");
FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p); FileUtils.ExtractToDirectory(GetTestFile(testFile), output, p => progress = p);
Assert.Equal(1, progress); await Assert.That(progress).IsEqualTo(1);
Assert.Contains(containsText, File.ReadAllText(PathUtils.WithLongPath(Path.Combine(output, Path.GetFileNameWithoutExtension(testFile))))); await Assert.That(File.ReadAllText(PathUtils.ToExtendedFormat(Path.Combine(output, PathUtils.GetFileNameWithoutExtension(testFile))))).Contains(containsText);
} }
[Theory] [Test]
[InlineData("Corrupted.zip")] [Arguments("Corrupted.zip")]
[InlineData("Not zip.zip")] [Arguments("Not zip.zip")]
public void Compression_ReadBad(string testFile) { public void 解压_ReadBad(string testFile)
Assert.Throws<InvalidDataException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder)); => Assert.Throws<InvalidDataException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder));
}
[Theory] [Test]
[InlineData("DotDot ZipSlip.zip")] [Arguments("DotDot ZipSlip.zip")]
[InlineData("AbsPath ZipSlip.zip")] [Arguments("AbsPath ZipSlip.zip")]
public void Compression_ZipSlip(string testFile) { public void 解压_ZipSlip(string testFile)
Assert.Throws<FileUtils.ZipSlipException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder)); => Assert.Throws<FileUtils.ZipSlipException>(() => FileUtils.ExtractToDirectory(GetTestFile(testFile), tempFolder));
}
#endregion #endregion
+104
View File
@@ -0,0 +1,104 @@
namespace MeloongCore.Tests;
public class PathUtilsTests : TestBase {
#region 路径处理
[Test]
[Arguments(@"\\?\C:\foo\bar.txt", @"\\?\C:\foo")]
[Arguments(@"C:\foo\extra/bar.txt", @"C:\foo\extra")]
[Arguments(@"C:\foo/extra/bar.txt", @"C:\foo/extra")]
[Arguments(@"C:\foo/extra\bar.txt", @"C:\foo/extra")]
[Arguments(@"C:\foo\bar.txt", @"C:\foo")]
[Arguments(@"\\?\C:\foo\Bar", @"\\?\C:\foo")]
[Arguments(@"C:\foo\bar", @"C:\foo")]
[Arguments(@"C:\Foo\bar\", @"C:\Foo")]
[Arguments(@"\\?\C:\foo\", @"\\?\C:")]
[Arguments(@"C:\foo", @"C:")]
[Arguments(@"C:\foo\", @"C:")]
[Arguments(@"https://foo.bar/file\long/pack.zip?arg=1", @"https://foo.bar/file\long")]
[Arguments(@"https://foo.bar/file\long\pack.zip?arg=1", @"https://foo.bar/file\long")]
[Arguments(@"https://foo.bar/file/long\pack.zip?arg=1", @"https://foo.bar/file/long")]
[Arguments(@"https://foo.bar/file/long/pack.zip?arg=1", @"https://foo.bar/file/long")]
[Arguments(@"https://foo.bar/file/", "https://foo.bar")]
[Arguments(@"https://foo.bar/file/?arg=1", "https://foo.bar")]
[Arguments(@"https://foo.bar/file?arg=1", "https://foo.bar")]
public async Task 路径处理_RemoveLastPart(string input, string expected)
=> await Assert.That(PathUtils.RemoveLastPart(input)).IsEqualTo(expected);
[Test]
[Arguments(@"\\?\C:\foo\bar.txt", "bar.txt")]
[Arguments(@"C:\foo\extra/bar.txt", "bar.txt")]
[Arguments(@"C:\foo/extra/bar.txt", "bar.txt")]
[Arguments(@"C:\foo/extra\bar.txt", "bar.txt")]
[Arguments(@"C:\foo\bar.txt", "bar.txt")]
[Arguments(@"C:\foo\bar.txt", "bar.txt")]
[Arguments(@"\\?\C:\foo/bar", "bar")]
[Arguments(@"C:\foo\bar", "bar")]
[Arguments(@"C:\foo\bar\", "bar")]
[Arguments(@"\\?\C:\foo\", "foo")]
[Arguments(@"C:\foo", "foo")]
[Arguments(@"C:\foo\", "foo")]
[Arguments(@"https://foo.bar/file\long/pack.zip?arg=1", "pack.zip")]
[Arguments(@"https://foo.bar/file\long\pack.zip?arg=1", "pack.zip")]
[Arguments(@"https://foo.bar/file/long\pack.zip?arg=1", "pack.zip")]
[Arguments(@"https://foo.bar/file/long/pack.zip?arg=1", "pack.zip")]
[Arguments(@"https://foo.bar/file/", "file")]
[Arguments(@"https://foo.bar/file/?arg=1", "file")]
[Arguments(@"https://foo.bar/File?arg=1", "File")]
[Arguments(@"https://cdn.modrinth.com/data/RvfAlf4Z/versions/XauQUBeR\Redstone Tweaks 2.5.3.zip?mr_download_reason=modpack", "Redstone Tweaks 2.5.3.zip")]
public async Task 路径处理_GetLastPart(string input, string expected)
=> await Assert.That(PathUtils.GetLastPart(input)).IsEqualTo(expected);
[Test]
[Arguments(@"\\?\C:\foo\bar.txt", "bar")]
[Arguments(@"C:\foo\bar.2.txt", "bar.2")]
[Arguments(@"\\?\C:\foo\bar", "bar")]
[Arguments(@"C:\foo\bar", "bar")]
[Arguments(@"C:\foo.bar\how/long\path.txt", "path")]
[Arguments(@"C:\foo.bar\how/long/path.txt", "path")]
[Arguments(@"C:\foo.bar\how\long/path.txt", "path")]
[Arguments(@"C:\foo.bar\how\", "how")]
[Arguments(@"\\?\C:\foo\", "foo")]
[Arguments(@"C:\foo", "foo")]
[Arguments(@"C:\foo\", "foo")]
[Arguments(@"cREate.jar.disabled", "cREate.jar")]
[Arguments(@"create.jar", "create")]
[Arguments(@"create", "create")]
[Arguments(@"https://foo.bar/file\long/pack.zip?arg=1", "pack")]
[Arguments(@"https://foo.bar/file\long\pack.zip?arg=1", "pack")]
[Arguments(@"https://foo.bar/file/long\pack.zip?arg=1", "pack")]
[Arguments(@"https://foo.bar/file/long/pack.zip?arg=1", "pack")]
[Arguments(@"https://foo.bar/file/page.xaml.vb?arg=1", "page.xaml")]
[Arguments(@"https://foo.bar/some.how/file/", "file")]
[Arguments(@"https://foo.bar/file/?arg=1", "file")]
[Arguments(@"https://foo.bar/file?arg=1", "file")]
public async Task 路径处理_GetFileNameWithoutExtension(string input, string expected)
=> await Assert.That(PathUtils.GetFileNameWithoutExtension(input)).IsEqualTo(expected);
[Test]
[Arguments(@"\\?\C:\FOO\BAR.TXT", "txt")]
[Arguments(@"C:\foo\bar.txt", "txt")]
[Arguments(@"C:\foo.bar\how/long\path.txt", "txt")]
[Arguments(@"C:\foo.bar\how/long/path.txt", "txt")]
[Arguments(@"C:\foo.bar\how\long/path.txt", "txt")]
[Arguments(@"\\?\C:\foo\bar", "")]
[Arguments(@"C:\foo\bar", "")]
[Arguments(@"C:\foo\bar\", "")]
[Arguments(@"\\?\C:\foo\", "")]
[Arguments(@"C:\foo", "")]
[Arguments(@"C:\foo\", "")]
[Arguments("create.jar.diSAbled", "disabled")]
[Arguments(@"https://foo.bar/file\long/pack.zip?arg=1", "zip")]
[Arguments(@"https://foo.bar/file\long\pack.zip?arg=1", "zip")]
[Arguments(@"https://foo.bar/file/long\pack.zip?arg=1", "zip")]
[Arguments("https://foo.bar/file/page.xaml.vb?arg=1", "vb")]
[Arguments("https://foo.bar/file/long/pack.ZIP?arg=1", "zip")]
[Arguments("https://foo.bar/file/", "")]
[Arguments("https://foo.bar/file/?arg=1", "")]
[Arguments("https://foo.bar/file?arg=1", "")]
public async Task 路径处理_GetExtension(string input, string expected)
=> await Assert.That(PathUtils.GetExtension(input)).IsEqualTo(expected);
#endregion
}
+2 -1
View File
@@ -3,6 +3,7 @@
namespace MeloongCore.Wpf.Extensions; namespace MeloongCore.Wpf.Extensions;
public static class WpfExtensions { public static class WpfExtensions {
public static bool Any(this UIElementCollection? Arr) => Arr?.Count > 0; public static bool Any(this UIElementCollection? arr)
=> arr?.Count > 0;
} }
+86
View File
@@ -0,0 +1,86 @@
using Microsoft.Win32;
namespace MeloongCore.Wpf;
public static class Dialogs {
/// <summary>
/// 弹出 “保存” 弹窗,返回用户指定的路径,若取消则返回 <c>null</c>。
/// <para/> <paramref name="filter"/> 中的扩展名不加 <c>.</c>。
/// </summary>
public static string? SaveFile(string title, string defaultFileName = "", string? defaultDirectory = null, IEnumerable<(string Extension, string Display)>? filter = null) {
var filters = filter?.ToList();
var dialog = new SaveFileDialog {
AddExtension = true,
Title = title,
FileName = defaultFileName
};
if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.InitialDirectory = PathUtils.ToShortPath(defaultDirectory!);
if (filters != null) {
dialog.Filter = filters.Select(f => $"{f.Display}(*.{f.Extension})|*.{f.Extension}").Join("|");
}
Logger.Info($"保存弹窗:{dialog.Title}(FileName={dialog.FileName}, InitialDirectory={dialog.InitialDirectory}, Filter={dialog.Filter})");
if (dialog.ShowDialog() != true) return null;
var result = dialog.FileName;
Logger.Info($"保存弹窗返回:{result}");
if (!result.Contains(Path.DirectorySeparatorChar)) return null;
// AddExtension 可能失效,需要手动补全(#8214)
if (filters != null && !string.IsNullOrEmpty(result) && !filters.Any(f => result.EndsWithF("." + f.Extension))) {
result += "." + filters[dialog.FilterIndex - 1].Extension;
Logger.Warn($"选择文件的返回无扩展名,将会手动添加,修改后为:{result}");
}
return result;
}
/// <summary>
/// 弹出 “选择文件” 弹窗,返回用户选择的文件路径,若取消则返回空数组。
/// <para/> <paramref name="filter"/> 中的扩展名不加 <c>.</c>。
/// </summary>
public static List<string> SelectFile(string title, bool multiselect, string? defaultDirectory = null, IEnumerable<(string[] Extensions, string Display)>? filter = null) {
var filters = filter?.ToList();
var dialog = new OpenFileDialog {
AddExtension = true,
CheckFileExists = true,
Multiselect = multiselect,
Title = title,
ValidateNames = true
};
if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.InitialDirectory = PathUtils.ToShortPath(defaultDirectory!);
if (filters != null) {
dialog.Filter = filters.Select(f => {
var exts = string.Join(";", f.Extensions.Select(e => $"*.{e}"));
return $"{f.Display}({exts})|{exts}";
}).Join("|");
}
Logger.Info($"选择文件弹窗:{dialog.Title}(Multiselect={dialog.Multiselect}, InitialDirectory={dialog.InitialDirectory}, Filter={dialog.Filter})");
if (dialog.ShowDialog() != true) return [];
var results = dialog.FileNames.Where(f => f.Contains(Path.DirectorySeparatorChar)).ToList();
Logger.Info($"选择文件弹窗返回:{results.Join(",")}");
return results;
}
/// <summary>
/// 弹出 “选择文件夹” 弹窗,返回用户选择的文件夹路径(以分隔符结尾),若取消则返回空数组。
/// </summary>
public static List<string> SelectFolder(string title, bool multiselect, string? defaultDirectory = null) {
var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog {
ShowNewFolderButton = true,
Description = title,
Multiselect = multiselect,
UseDescriptionForTitle = true
};
if (!string.IsNullOrEmpty(defaultDirectory) && DirectoryUtils.Exists(defaultDirectory!)) dialog.SelectedPath = defaultDirectory;
Logger.Info($"选择文件夹弹窗:{dialog.Description}(Multiselect={dialog.Multiselect}, SelectedPath={dialog.SelectedPath})");
if (dialog.ShowDialog() != true) return [];
var results = dialog.SelectedPaths.Where(f => f.Contains(Path.DirectorySeparatorChar)).Select(PathUtils.AddSlashSuffix).ToList();
Logger.Info($"选择文件夹弹窗返回:{results.Join(",")}");
return results;
}
}
+74
View File
@@ -0,0 +1,74 @@
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace MeloongCore.Wpf;
/// <summary>
/// 对数据绑定进行加法运算,使用 <paramref name="parameter"/> 决定加数。
/// </summary>
public class AdditionConverter : IValueConverter {
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is null) return 0;
if (!double.TryParse(value.ToString(), out double before)) return 0;
double scale = 1;
if (parameter is not null) double.TryParse(parameter.ToString(), out scale);
return before + scale;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is null) return Binding.DoNothing;
if (!double.TryParse(value.ToString(), out double before)) return Binding.DoNothing;
double scale = 1;
if (parameter is not null) double.TryParse(parameter.ToString(), out scale);
return before - scale;
}
}
/// <summary>
/// 对数据绑定进行乘法运算,使用 <paramref name="parameter"/> 决定乘数。
/// </summary>
public class MultiplicationConverter : IValueConverter {
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is null) return 0;
if (!double.TryParse(value.ToString(), out double before)) return 0;
double scale = 1;
if (parameter is not null) double.TryParse(parameter.ToString(), out scale);
return before * scale;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is null) return Binding.DoNothing;
if (!double.TryParse(value.ToString(), out double before)) return Binding.DoNothing;
double scale = 1;
if (parameter is not null) double.TryParse(parameter.ToString(), out scale);
if (scale == 0) return Binding.DoNothing;
return before / scale;
}
}
/// <summary>
/// 将取反的 <see cref="bool"/> 绑定到 <see cref="Visibility"/>。
/// </summary>
public class InverseBooleanToVisibilityConverter : IValueConverter {
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is null) return Visibility.Visible;
return bool.TryParse(value.ToString(), out bool boolValue) ? (boolValue ? Visibility.Collapsed : Visibility.Visible) : Visibility.Visible;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is null) return false;
return value is Visibility vis && vis != Visibility.Visible;
}
}
/// <summary>
/// 将 <see cref="bool"/> 取反。
/// </summary>
public class InverseBooleanConverter : IValueConverter {
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is null) return false;
return bool.TryParse(value.ToString(), out bool boolValue) ? !boolValue : false;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is null) return false;
return bool.TryParse(value.ToString(), out bool boolValue) ? !boolValue : false;
}
}
+3
View File
@@ -15,6 +15,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
<PackageReference Include="PolySharp" Version="1.15.0"> <PackageReference Include="PolySharp" Version="1.15.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -38,6 +39,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System.Windows.Forms" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" /> <Reference Include="PresentationFramework" />
</ItemGroup> </ItemGroup>