Recursively Delete a Directory Structure
So you want to delete a directory programmatically, but you're not quite sure just how to do it? You're vaguely aware that the process requires this nasty thing called "Recursion", but the very act of uttering the word causes a negative physical reaction? Don't sweat it. We've all been there.
Yes, recursion can sometimes be a difficult topic to wrap your mind around. But the process of deleting a directory (with all of its subdirectories) is actually a great place to start the learning process. It's a great place because it's a concept that we're all already familiar with. I mean, we must delete umpteen directories every week, right? So we're not going to have to try and grapple with the problem domain and the algorithm at the same time.
There are many definitions of the general term "Recursion" (often having to do with a mathematical operation being defined in terms of itself). In Computer Science, however, we get a little more specific than that. Recursion, to us programmers, describes a situation where a function calls itself. There are some problems (like traversing all of the nodes in a tree, or deleting a directory structure) that are extremely easy to solve within the context of a function that can call itself. Those same problems, however, are often painfully difficult to solve (or horribly inefficient) if another approach is taken.
The following code is an example (a horrible example) of a recursive function:
That function does exactly what it implies: It merrily goes nowhere....forever. This is obviously a problem, right? A single call to MerrilyGoNowhere() will bring the walls of reality shattering down around us, leaving our program as little more than a steaming pile of hot rubbish. Well, maybe not that drastic, but at the very least we've just entered the shadowy-realm of the non-terminating loop. It's a place we don't want to be.
The problem is that it's a place you might frequent until you get over the initial learning curve of recursion. There must be a step, somewhere in that function, that steps us back out of the recursion and up the call stack. Let's refactor a little bit.
The key to recursion is to only recurse conditionally. Some set of circumstances must be true in order for you to take the recursive step. Otherwise, you step out of the function, which steps back up the call stack and stops your function from creating a non-terminating loop. The "Else" block above isn't technically required, but it demonstrates that you can do some other processing if your recursion condition isn't met.
Take a quick walk through the code above, step by step:
We launch our program, and a call to MerrilyGoNowhere() takes place.
- On this first pass, let's say that WeHaveEnoughEnergy() returns "true", so we call MerrilyGoNowhere() again.
- On the 2nd pass, WeHaveEnoughEnergy() returns "true" again, so we call MerrilyGoNowhere() Again.
- On the 3rd pass, however, let's say that WeHaveEnoughEnergy() returns "false". In this case, we skip the recursive step and go straight to "GetSomeRest".
- The function then returns up the call stack to the previous call (the 2nd call) to MerrilyGoNowhere(). However, no further processing is required in that function, so we return up the call stack to the previous call (the 1st call) to MerrilyGoNowhere().
- Once again, we find that no further processing is required, so we return up the call stack once more. On this return, we've completely left MerrilyGoNowhere() behind, and our program can continue or shut down gracefully, having avoided a non-terminating loop.
First, some groundwork. We know that in order to delete a directory structure, we're obviously going to need to delete the files in those directories, right? In fact, programmatically, we need to delete the files prior to attempting to delete the directory. Let's write a simple function that handles deleting a file:

As you can see it's a fairly simple program. It merely sets the attributes of a given file (Element) to FileAttributes.Normal and then attempts to delete that file. I've written the code in such a way that if an exception occurs, the function returns false. Otherwise, we return true. You don't have to make a separate function to handle file deletions. I just did so to clean up the code you'll see below.
Ok, so we have a function that will delete a file that we pass to it. So how do we delete the directory structure? Well, recursively, of course! Let's look at the following code:

Here we can see that recursion is our friend once again. The function takes one parameter "directoryPath", which is the fully-qualified path to the directory we want to delete.
Let's walk through the code:
- We call "DeleteDirectory()" and pass it a path to the directory we want to delete.
- We check to see if that directory actually exists. If it does not, we display an error message.
- Get a list of all of the elements in the directory.
- Begin looping through those elements. If we find that the current element we are looping through is itself a directory, then we call DeleteDirectory once more, passing it that element (which we now know to be a path to a subdirectory).
- This process continues until we find an element that is actually a file. When we find a file, we simply make a call to DeleteFile(), passing it the file we just discovered.
- When no additional files or directories are found, the function returns up the call stack.
- The next line of code deletes the now-empty directory.




