C# – Find all empty directories

Let’s say you want to search the file system and find all empty directories. An empty directory has the following conditions:

  • It has no files.
  • It either has no subdirectories -OR- it only has empty subdirectories.

To check if a directory is empty, you have to recursively check all of its subdirectories for any files. Use Directory.EnumerateDirectories() to loop through a directory’s immediate subdirectories, and use Directory.EnumerateFiles().Any() to check for files. The following code shows how to do this:

using System.IO; using System.Linq; bool IsDirectoryEmpty(string path) { bool subDirectoriesAreEmpty = true; foreach (var subDir in Directory.EnumerateDirectories(path)) { if (IsDirectoryEmpty(subDir)) { Console.WriteLine($"Empty: {subDir}"); } else { subDirectoriesAreEmpty = false; } } if (subDirectoriesAreEmpty && !Directory.EnumerateFiles(path).Any()) { return true; } return false; }
Code language: C# (cs)

Note: You can use this as a starting point for dealing with empty directories however you need to. This is simply outputting the paths to the console.

Now I’ll show an example of running this code against a directory – C:\temp\EmptyTest\ – with the following structure:

Folder tree - starting with C:\temp\EmptyTest at the root and containing several sub-folders

As you can see, this directory contains four empty subdirectories. Here’s how to run the code against this directory:

string rootPath = @"C:\temp\EmptyTest\"; Console.WriteLine($"Finding all empty directories in {rootPath}"); if (IsDirectoryEmpty(rootPath)) { Console.WriteLine("Empty all the way down"); }
Code language: C# (cs)

This correctly finds the four empty subdirectories and outputs the following:

Finding all empty directories in C:\temp\EmptyTest\ Empty: C:\temp\EmptyTest\B-NotEmpty\BB-Empty Empty: C:\temp\EmptyTest\C-Empty Empty: C:\temp\EmptyTest\D-Empty\DD-Empty Empty: C:\temp\EmptyTest\D-Empty
Code language: plaintext (plaintext)

The root directory is not empty. It contains at least one subdirectory that has files, so by definition, it’s not empty.

Leave a Comment