C# – Find all empty folders

An empty folder:

  • Has no files.
  • Either has no folders, or has folders that are empty.

In this article I’ll show code that finds empty folders based on this definition.

Code that finds empty folders

Given a root folder path, the following code recursively looks for empty folders and writes the empty folder path to the console.

static void Main(string[] args) { string rootPath = @"C:\temp\EmptyFolderFinderTest"; Console.WriteLine($"Finding all empty folders in {rootPath}"); if(IsEmpty(rootPath)) { Console.WriteLine("Empty all the way down"); } } private static bool IsEmpty(string folderPath) { bool allSubFoldersEmpty = true; foreach(var subFolder in Directory.EnumerateDirectories(folderPath)) { if (IsEmpty(subFolder)) { Console.WriteLine($"Empty: {subFolder}"); } else { allSubFoldersEmpty = false; } } if(allSubFoldersEmpty && !HasFiles(folderPath)) { return true; } return false; } private static bool HasFiles(string folderPath) { return Directory.EnumerateFiles(folderPath).Any(); }

Results – finding empty folders

I ran this against the root folder C:\temp\EmptyFolderFinderTest\, which has the following structure:

  • \ThisHasAHiddenFile\
    • log.txt (hidden)
  • \ThisHasFoldersWithStuffInThem\
    • \Empty\
    • \HasAFile\
      • log.txt
  • \ThisIsEmpty\
  • \ThisOnlyHasEmptyFolders\
    • \Empty\

It correctly found all of the empty folders:

Leave a Comment