I think I formerly knew how to do this, but it seems that I have forgotten.
I have a recursive algorithm to remove all empty directories in a directory tree:
static bool DeleteDirectoriesRecursive(string path)
{
var remove = true;
foreach (var dir in System.IO.Directory.GetDirectories(path))
{
remove &= DeleteDirectoriesRecursive(dir);
}
if (remove &= (System.IO.Directory.GetFiles(path).Length == 0))
System.IO.Directory.Delete(path);
return remove;
}
I'm trying to eliminate the recursion from this algorithm, not so much to "fix" the algorithm (i.e., the similar question doesn't use the remove
variable, but I would like to keep it).
I have started a new function, using the Stack<>
class, but I can't think of a good way to return to the base path and take the actions that the sub-directories have determined. I guess unraveling non-tail recursion takes a bit more effort.