FileSystemHelper.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using MediaBrowser.Model.IO;
  5. using Microsoft.Extensions.Logging;
  6. namespace MediaBrowser.Controller.IO;
  7. /// <summary>
  8. /// Helper methods for file system management.
  9. /// </summary>
  10. public static class FileSystemHelper
  11. {
  12. /// <summary>
  13. /// Deletes the file.
  14. /// </summary>
  15. /// <param name="fileSystem">The fileSystem.</param>
  16. /// <param name="path">The path.</param>
  17. /// <param name="logger">The logger.</param>
  18. public static void DeleteFile(IFileSystem fileSystem, string path, ILogger logger)
  19. {
  20. try
  21. {
  22. fileSystem.DeleteFile(path);
  23. }
  24. catch (UnauthorizedAccessException ex)
  25. {
  26. logger.LogError(ex, "Error deleting file {Path}", path);
  27. }
  28. catch (IOException ex)
  29. {
  30. logger.LogError(ex, "Error deleting file {Path}", path);
  31. }
  32. }
  33. /// <summary>
  34. /// Recursively delete empty folders.
  35. /// </summary>
  36. /// <param name="fileSystem">The fileSystem.</param>
  37. /// <param name="path">The path.</param>
  38. /// <param name="logger">The logger.</param>
  39. public static void DeleteEmptyFolders(IFileSystem fileSystem, string path, ILogger logger)
  40. {
  41. foreach (var directory in fileSystem.GetDirectoryPaths(path))
  42. {
  43. DeleteEmptyFolders(fileSystem, directory, logger);
  44. if (!fileSystem.GetFileSystemEntryPaths(directory).Any())
  45. {
  46. try
  47. {
  48. Directory.Delete(directory, false);
  49. }
  50. catch (UnauthorizedAccessException ex)
  51. {
  52. logger.LogError(ex, "Error deleting directory {Path}", directory);
  53. }
  54. catch (IOException ex)
  55. {
  56. logger.LogError(ex, "Error deleting directory {Path}", directory);
  57. }
  58. }
  59. }
  60. }
  61. }