FileHelper.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. namespace Admin.NET.Core;
  7. /// <summary>
  8. /// 文件帮助类
  9. /// </summary>
  10. public static class FileHelper
  11. {
  12. /// <summary>
  13. /// 尝试删除文件/目录
  14. /// </summary>
  15. /// <param name="path"></param>
  16. /// <returns></returns>
  17. public static bool TryDelete(string path)
  18. {
  19. try
  20. {
  21. if (string.IsNullOrEmpty(path)) return false;
  22. if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
  23. else File.Delete(path);
  24. return true;
  25. }
  26. catch (Exception)
  27. {
  28. // ignored
  29. return false;
  30. }
  31. }
  32. /// <summary>
  33. /// 复制目录
  34. /// </summary>
  35. /// <param name="sourceDir"></param>
  36. /// <param name="destinationDir"></param>
  37. /// <param name="overwrite"></param>
  38. public static void CopyDirectory(string sourceDir, string destinationDir, bool overwrite = false)
  39. {
  40. // 检查源目录是否存在
  41. if (!Directory.Exists(sourceDir)) throw new DirectoryNotFoundException("Source directory not found: " + sourceDir);
  42. // 如果目标目录不存在,则创建它
  43. if (!Directory.Exists(destinationDir)) Directory.CreateDirectory(destinationDir!);
  44. // 获取源目录下的所有文件并复制它们
  45. foreach (string file in Directory.GetFiles(sourceDir))
  46. {
  47. string name = Path.GetFileName(file);
  48. string dest = Path.Combine(destinationDir, name);
  49. File.Copy(file, dest, overwrite);
  50. }
  51. // 递归复制所有子目录
  52. foreach (string directory in Directory.GetDirectories(sourceDir))
  53. {
  54. string name = Path.GetFileName(directory);
  55. string dest = Path.Combine(destinationDir, name);
  56. CopyDirectory(directory, dest, overwrite);
  57. }
  58. }
  59. }