DirectoryUtils.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. namespace MeloongCore;
  2. public static class DirectoryUtils {
  3. /// <summary>
  4. /// 创建文件夹,或文件所在的文件夹。
  5. /// 文件夹已存在时不会抛出异常。
  6. /// </summary>
  7. public static void Create(string path) {
  8. if (DirectoryUtils.Exists(path)) return;
  9. Logger.Trace($"新建文件夹:{path}");
  10. path = PathUtils.WithLongPath(path);
  11. Directory.CreateDirectory(path);
  12. }
  13. /// <summary>
  14. /// 判断文件夹是否存在。
  15. /// </summary>
  16. public static bool Exists(string path)
  17. => Directory.Exists(PathUtils.WithLongPath(path));
  18. /// <summary>
  19. /// 获取 <see cref="DirectoryInfo"/> 对象。
  20. /// </summary>
  21. public static DirectoryInfo GetInfo(string path)
  22. => new(PathUtils.WithLongPath(path));
  23. /// <summary>
  24. /// 返回指定路径下的所有文件,不以 \\?\ 开头。
  25. /// 如果文件夹不存在,返回空列表。
  26. /// </summary>
  27. public static IEnumerable<string> GetFiles(string path, bool topDirectoryOnly = false, string searchPattern = "*") {
  28. if (!DirectoryUtils.Exists(path)) return [];
  29. return Directory.EnumerateFiles(PathUtils.WithLongPath(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories).
  30. Select(PathUtils.WithoutLongPath);
  31. }
  32. /// <summary>
  33. /// 返回指定路径下的所有文件夹,不以分隔符结尾,不以 \\?\ 开头。
  34. /// 如果文件夹不存在,返回空列表。
  35. /// </summary>
  36. public static IEnumerable<string> GetDirectories(string path, bool topDirectoryOnly = false, string searchPattern = "*") {
  37. if (!DirectoryUtils.Exists(path)) return [];
  38. return Directory.EnumerateDirectories(PathUtils.WithLongPath(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories).
  39. Select(PathUtils.WithoutLongPath);
  40. }
  41. /// <summary>
  42. /// 该文件夹是否为空。
  43. /// 如果文件夹不存在,返回 true。
  44. /// </summary>
  45. public static bool IsEmpty(string path) {
  46. if (!DirectoryUtils.Exists(path)) return true;
  47. return !Directory.EnumerateFileSystemEntries(PathUtils.WithLongPath(path)).Any();
  48. }
  49. /// <summary>
  50. /// 复制文件夹。
  51. /// 若原文件夹不存在,则不执行。
  52. /// </summary>
  53. public static void Copy(string sourceFolder, string destFolder, Action<double>? progressHandler = null) {
  54. if (!DirectoryUtils.Exists(sourceFolder)) {
  55. Logger.Info($"尝试复制文件夹,但原文件夹不存在,已跳过复制:{sourceFolder} → {destFolder}");
  56. progressHandler?.Invoke(1);
  57. return;
  58. }
  59. sourceFolder = PathUtils.Normalize(sourceFolder, true);
  60. destFolder = PathUtils.Normalize(destFolder, true);
  61. int doneCount = 0;
  62. Lazy<int> totalCount = new(() => DirectoryUtils.GetFiles(sourceFolder).Count());
  63. Logger.Trace($"复制文件夹:{sourceFolder} → {destFolder}");
  64. foreach (var file in DirectoryUtils.GetFiles(sourceFolder)) {
  65. FileUtils.Copy(file, file.Replace(sourceFolder, destFolder));
  66. doneCount++;
  67. if (progressHandler is not null) progressHandler?.Invoke((double) doneCount / totalCount.Value);
  68. }
  69. }
  70. /// <summary>
  71. /// 剪切文件夹。
  72. /// </summary>
  73. public static void Move(string sourceFolder, string destFolder) {
  74. if (!DirectoryUtils.Exists(sourceFolder)) return;
  75. DirectoryUtils.Delete(destFolder); // Move 要求不存在对应文件夹
  76. Logger.Trace($"剪切文件夹:{sourceFolder} → {destFolder}");
  77. Directory.Move(PathUtils.WithLongPath(sourceFolder), PathUtils.WithLongPath(destFolder));
  78. }
  79. /// <summary>
  80. /// 删除文件夹。
  81. /// </summary>
  82. public static void Delete(string folder, bool toRecycleBin = false) {
  83. // 安全检查
  84. if (!DirectoryUtils.Exists(folder)) return;
  85. Logger.Trace($"{(toRecycleBin ? "将文件夹删除到回收站" : "删除文件夹")}:{folder}");
  86. folder = PathUtils.Normalize(folder, true);
  87. if (folder == Path.GetPathRoot(folder))
  88. throw new UnauthorizedAccessException($"不应删除磁盘根目录:{folder}");
  89. if (criticalFolders.Value.Any(f => f.StartsWithF(folder, ignoreCase: true)))
  90. throw new UnauthorizedAccessException($"不应删除的文件夹:{folder}");
  91. // 删除
  92. if (toRecycleBin) {
  93. FileUtils.DeleteToRecycleBin(folder); // 删除到回收站
  94. } else {
  95. DeleteInternal(folder); // 永久删除
  96. static void DeleteInternal(string folder) {
  97. try {
  98. folder = PathUtils.WithLongPath(folder);
  99. foreach (string filePath in DirectoryUtils.GetFiles(folder, true)) FileUtils.Delete(filePath); // 删除文件
  100. foreach (string str in DirectoryUtils.GetDirectories(folder, true)) DeleteInternal(str); // 递归删除子文件夹
  101. ResilientUtils.RetryOn<IOException>(() => Directory.Delete(folder, true)); // 最终删除文件夹
  102. } catch (DirectoryNotFoundException ex) { // #4549,也可能已被其他线程删除
  103. if (DirectoryUtils.Exists(folder)) {
  104. Logger.Warn(ex, $"该文件夹可能为孤立的符号链接,尝试直接删除({folder})");
  105. Directory.Delete(folder, true);
  106. } else {
  107. throw;
  108. }
  109. }
  110. }
  111. }
  112. }
  113. private static readonly Lazy<HashSet<string>> criticalFolders = new(() => new(new[] {
  114. PathUtils.CurrentFolder,
  115. Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
  116. Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
  117. Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
  118. Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads") // 下载文件夹没有 SpecialFolder 枚举
  119. }.Select(f => PathUtils.Normalize(f, true))));
  120. }