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