The Empty-Folder Utility I Built—and the Checks I Would Add Now

Editorial illustration.

Originally published 16 June 2023; rewritten and reviewed on 15 October 2026.

Every developer who has worked on Windows long enough eventually ends up with a messy project drive. Years of extracted ZIP archives, client asset dumps, old IIS deployment folders, and half-cleaned backups leave behind dozens of hollow directory trees. I kept clicking into folders expecting to find old source files or images, only to stare at a blank Explorer window.

Instead of hunting them down one by one, I wrote a small Windows desktop utility in C# to scan a folder, count the empty directories, and clear them out. Looking back at the screenshots from 2023, the UI did its job for a quick personal tool—pick a root path, scan, and delete.

If I were rewriting that same utility today for daily use, the UI wouldn’t change much, but the filesystem logic underneath would.

Count entries, not only files

The classic mistake in a first-draft folder cleaner is checking for files recursively and assuming zero files means an empty folder:

// Fragile: returns true even if the folder contains subdirectories
bool hasNoFiles = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Length == 0;

Two things go wrong here. First, GetFiles allocates an entire string[] in memory before returning, which is wasteful on large trees. Second, a folder with zero files can still contain subdirectories—or be a parent folder whose child folders hold something else, or simply a tree of nested empty folders that need to be removed from the bottom up.

A tighter definition of an empty directory is one that has zero filesystem entries of any kind (neither files nor subdirectories):

static bool IsEmptyDirectory(string path)
{
    if (!Directory.Exists(path))
        return false;

    using var entries = Directory.EnumerateFileSystemEntries(path).GetEnumerator();
    return !entries.MoveNext();
}

EnumerateFileSystemEntries stops as soon as it sees the first item, so it doesn’t waste time reading thousands of entries in a busy node_modules or bin directory.

Even then, you still have to decide what “empty” means for your workflow. On Windows and macOS shares, folders often look empty to you while quietly holding hidden metadata like desktop.ini, Thumbs.db, or .DS_Store. Decide explicitly whether those count as real content or ignorable clutter; never assume they aren’t there.

Walk bottom-up and guard against edge cases

When a parent folder only contains an empty child folder, deleting the child makes the parent empty too. A top-down pass misses the parent unless you re-scan. Walking bottom-up (post-order traversal) solves this cleanly in one pass: visit children first, and check the parent afterwards.

Just as important is what you refuse to touch:

  • Skip reparse points and junctions: Windows uses directory junctions and OneDrive placeholders heavily. Following a reparse point (FileAttributes.ReparsePoint) without checking can send your scanner into a completely different drive or cloud-synced folder.
  • Block system and profile roots: Hardcode a guard against C:\, C:\Windows, Program Files, and AppData unless the user explicitly targets a specific subfolder inside them.
  • Handle UnauthorizedAccessException and IOException per directory: One locked folder shouldn’t crash the whole scan or abort the remaining cleanup.

Here is how I would structure a safe post-order candidate collector in modern C#:

static void CollectEmptyDirectories(
    string root,
    IList<string> candidates,
    IList<string> errors)
{
    var dirInfo = new DirectoryInfo(root);
    if (!dirInfo.Exists || dirInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
        return;

    try
    {
        foreach (var subDir in dirInfo.EnumerateDirectories())
        {
            CollectEmptyDirectories(subDir.FullName, candidates, errors);
        }

        // Empty now, or all child directories were themselves empty candidates
        bool hasFiles = dirInfo.EnumerateFiles().Any();
        bool hasRemainingSubdirs = dirInfo.EnumerateDirectories()
            .Any(d => !candidates.Contains(d.FullName));

        if (!hasFiles && !hasRemainingSubdirs)
        {
            candidates.Add(dirInfo.FullName);
        }
    }
    catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException)
    {
        errors.Add($"{root}: {ex.Message}");
    }
}

(In a larger tool with thousands of folders, replace candidates.Contains(...) with a HashSet<string>(StringComparer.OrdinalIgnoreCase) so lookups stay $O(1)$.)

Preview first and keep deletion recoverable

The best decision I made in the 2023 version was sending deleted folders to the Windows Recycle Bin instead of calling Directory.Delete(path, true) permanently. In .NET on Windows, Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory with RecycleOption.SendToRecycleBin gives you a built-in safety net if you realise an hour later that a build script expected a specific empty logs/ or temp/ folder to exist.

Before deleting anything, show the user the exact list of candidate paths in a preview pane with a checkbox or confirmation step. Then, right before deleting each folder in the loop, verify one last time that it is still empty—filesystem state is only a point-in-time snapshot, and another background process (like a sync client or IDE) can drop a file into a folder in the seconds between your scan and your click.

Never fall back to recursive deletion if Directory.Delete(path, recursive: false) throws because the folder is no longer empty. Skip it, log the reason, and report individual failures clearly at the end.

Before trusting any cleanup utility on real client archives, test it against a disposable folder tree containing four cases: truly empty nested folders, folders with hidden files, an inaccessible folder with restricted permissions, and a folder where a background script writes a file mid-run. Automation is only worth the clicks it saves when you know for sure it removes only what you meant to delete.

Images from the original article

The following images are retained as historical context; interfaces and configuration options may have changed.

Original article image 1: The Empty-Folder Utility I Built—and the Checks I Would Add Now

Original article image 2: The Empty-Folder Utility I Built—and the Checks I Would Add Now

Original article image 3: The Empty-Folder Utility I Built—and the Checks I Would Add Now