NielW NielW -4 years ago 202
C# Question

Delete all empty directories in specified path

In my program, I create a long branching tree of directories. When I'm done with certain files on the leaves of this tree, I delete them, but I end up with a lot of empty parent directories. I'd like to delete these as well. However, I can't just recursively delete all these parent directories, because some of them have children that I can't delete yet.

Example:
C:\MyProject\Project1\file1\file2\file3\file4\file5\document.txt

If I delete document.txt, I want to also delete all the other empty folders in the path. However, file 3 has something in it (besides file4), so I can't delete it or anything above it. So in this case, file4 and file5 would be deleted.

Consider the root directory to be Project1. I don't want to delete anything above that.

Has anyone written something to do this?

Basically, something I can call where I can specify the path I'm trying to remove from the tree (first arg below), along with the root of the tree (second arg).

DeleteEmptySubDirectoriesInPath("C:\MyProject\Project1\file1\file2\file3\file4\file5\",
"C:\MyProject\Project1");


Another way to look at it is the inverse of Directory.CreateDirectory. This is the function I used to generate these long branches. Now I need to remove them when I'm done without disturbing anything else.

Answer Source

A little bit of iteration would work:

var di = new DirectoryInfo(@"C:\MyProject\Project1\file1\file2\file3\file4\");
var root = @"C:\MyProject\Project1"; // no trailing slash!
while (di.FullName != root 
       && !di.EnumerateFiles().Any() 
       && !di.EnumerateDirectories().Any())
{
    di.Delete();
    di = di.Parent;
}

Start from the directory of interest; as long as there are no files and you have not reached the "root", delete it and move to its parent directory. Repeat until done.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download