Extension.IO.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.Collections.Generic;
  2. using System.IO;
  3. namespace TBL.CSharp.Base
  4. {
  5. public static partial class Extension
  6. {
  7. /// <summary>
  8. /// 目录削除
  9. /// </summary>
  10. public static void DirectoryDelete(this string path)
  11. {
  12. if (Directory.Exists(path))
  13. Directory.Delete(path, true);
  14. }
  15. /// <summary>
  16. /// 目录确保
  17. /// </summary>
  18. public static void DirectoryEnsure(this string path, bool clear = true)
  19. {
  20. if (clear)
  21. {
  22. DirectoryDelete(path);
  23. Directory.CreateDirectory(path);
  24. }
  25. else
  26. {
  27. if (!Directory.Exists(path))
  28. Directory.CreateDirectory(path);
  29. }
  30. }
  31. /// <summary>
  32. /// 移动目录
  33. /// </summary>
  34. public static void DirectoryMove(this string source, string target)
  35. {
  36. var stack = new Stack<(string Source, string Target)>();
  37. stack.Push((source, target));
  38. while (stack.Count > 0)
  39. {
  40. var folders = stack.Pop();
  41. Directory.CreateDirectory(folders.Target);
  42. foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
  43. {
  44. string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
  45. if (File.Exists(targetFile)) File.Delete(targetFile);
  46. File.Move(file, targetFile);
  47. }
  48. foreach (var folder in Directory.GetDirectories(folders.Source))
  49. {
  50. stack.Push((folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
  51. }
  52. }
  53. Directory.Delete(source, true);
  54. }
  55. }
  56. }