DirectoryUtils.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 = Path.GetDirectoryName(path);
  9. Directory.CreateDirectory(PathUtils.WithLongPath(path));
  10. }
  11. /// <summary>
  12. /// 判断文件夹是否存在。
  13. /// </summary>
  14. public static bool Exists(string path) {
  15. return Directory.Exists(PathUtils.WithLongPath(path));
  16. }
  17. /// <summary>
  18. /// 创建 <see cref="DirectoryInfo"/> 对象。
  19. /// </summary>
  20. public static DirectoryInfo GetInfo(string path) {
  21. return new(PathUtils.WithLongPath(path));
  22. }
  23. /// <summary>
  24. /// 返回指定路径下的所有文件,不以 \\?\ 开头。
  25. /// </summary>
  26. public static IEnumerable<string> GetFiles(string path, bool topDirectoryOnly = false, string searchPattern = "*") {
  27. if (!Exists(path)) return [];
  28. return Directory.EnumerateFiles(PathUtils.WithLongPath(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories).
  29. Select(PathUtils.WithoutLongPath);
  30. }
  31. /// <summary>
  32. /// 返回指定路径下的所有文件夹,不以分隔符结尾,不以 \\?\ 开头。
  33. /// </summary>
  34. public static IEnumerable<string> GetDirectories(string path, bool topDirectoryOnly = false, string searchPattern = "*") {
  35. if (!Exists(path)) return [];
  36. return Directory.EnumerateDirectories(PathUtils.WithLongPath(path), searchPattern, topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories).
  37. Select(PathUtils.WithoutLongPath);
  38. }
  39. /// <summary>
  40. /// 该文件夹是否为空。
  41. /// 如果文件夹不存在,也返回 true。
  42. /// </summary>
  43. public static bool IsEmpty(string path) {
  44. if (!Exists(path)) return true;
  45. return !Directory.EnumerateFileSystemEntries(PathUtils.WithLongPath(path)).Any();
  46. }
  47. /// <summary>
  48. /// 剪切文件夹。
  49. /// </summary>
  50. public static void Move(string sourceDirName, string destDirName) {
  51. if (!Exists(sourceDirName)) return;
  52. Create(destDirName);
  53. Directory.Move(PathUtils.WithLongPath(sourceDirName), PathUtils.WithLongPath(destDirName));
  54. }
  55. /// <summary>
  56. /// 删除文件夹。
  57. /// </summary>
  58. public static void Delete(string dirPath, bool toRecycleBin = false) {
  59. if (toRecycleBin) {
  60. if (Exists(dirPath)) FileUtils.DeleteToRecycleBin(dirPath);
  61. } else {
  62. Directory.Delete(PathUtils.WithLongPath(dirPath));
  63. }
  64. }
  65. }