From 254a8ce64cd39038e4a2e267e50c0910e39e71e2 Mon Sep 17 00:00:00 2001 From: ta264 Date: Fri, 13 Sep 2019 17:55:12 +0100 Subject: [PATCH] Fixed: Directory not empty exception deleting nested empty subdirs (#974) --- .../DiskTests/DiskProviderFixtureBase.cs | 15 +++++++++++++++ src/NzbDrone.Common/Disk/DiskProviderBase.cs | 12 ++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs index df228193f..a27a09fba 100644 --- a/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs +++ b/src/NzbDrone.Common.Test/DiskTests/DiskProviderFixtureBase.cs @@ -122,6 +122,21 @@ namespace NzbDrone.Common.Test.DiskTests Directory.Exists(sourceDir).Should().BeFalse(); } + [Test] + public void should_be_able_to_delete_nested_empty_subdirs() + { + var artistDir = Path.Combine(GetTempFilePath(), "Artist"); + var albumDir = Path.Combine(artistDir, "Album"); + + Directory.CreateDirectory(Path.Combine(albumDir)); + Directory.CreateDirectory(Path.Combine(albumDir, "Album")); + Directory.CreateDirectory(Path.Combine(albumDir, "Album", "CD1")); + Directory.CreateDirectory(Path.Combine(albumDir, "Album", "CD2")); + + Subject.RemoveEmptySubfolders(artistDir); + Directory.Exists(albumDir).Should().BeFalse(); + } + [Test] public void empty_folder_should_return_folder_modified_date() { diff --git a/src/NzbDrone.Common/Disk/DiskProviderBase.cs b/src/NzbDrone.Common/Disk/DiskProviderBase.cs index de37a7ac3..6bbbb3343 100644 --- a/src/NzbDrone.Common/Disk/DiskProviderBase.cs +++ b/src/NzbDrone.Common/Disk/DiskProviderBase.cs @@ -154,6 +154,13 @@ namespace NzbDrone.Common.Disk return _fileSystem.Directory.GetDirectories(path); } + public string[] GetDirectories(string path, SearchOption searchOption) + { + Ensure.That(path, () => path).IsValidPath(); + + return _fileSystem.Directory.GetDirectories(path, "*", searchOption); + } + public string[] GetFiles(string path, SearchOption searchOption) { Ensure.That(path, () => path).IsValidPath(); @@ -500,10 +507,11 @@ namespace NzbDrone.Common.Disk public void RemoveEmptySubfolders(string path) { - var subfolders = GetDirectories(path); + var subfolders = GetDirectories(path, SearchOption.AllDirectories); var files = GetFiles(path, SearchOption.AllDirectories); - foreach (var subfolder in subfolders) + // By sorting by length descending we ensure we always delete children before parents + foreach (var subfolder in subfolders.OrderByDescending(x => x.Length)) { if (files.None(f => subfolder.IsParentPath(f))) {