In a previous example we got a list of sub directories for a given parent directory. But what it couldn’t do, is get the list of directories, under any of those directories.
If we wanted to get all the children, grand children, great grand children, etc. of a directory, we need to rethink this process.
One thing to remember is that we know what the current sub directory is. And since we have it, and we have a function which lists sub directories for a directory that is passed to it, we can simply call this function again.
The process of a function calling itself is called recursion. In theory, a function can continue to call itself indefinitely, however, you will eventually run into a problem with running out of memory. But that is a different story.
You might look, and ask yourself, are we going to overwrite our variable values. The answer, in this case, is no. That is because we are declaring our variables inside our function, they are specific to this instance of the function call, and different from any other function call. How that works is more about compiler theory, so we aren’t going to cover it at this point.
Adding a recursion to the previous function is easy, after you print out the line of text, you just need to call the function, and pass the current directory name for the function parameter, like so:
static void getSubDirectories(string workingDirectory) { // get a list of directories for the directory that // is passed into our function string[] subDirectories = Directory.GetDirectories(workingDirectory); foreach (string subDirectory in subDirectories) { // use a foreach loop to go through each item in the // array, one at a time // print out current sub directory name Console.WriteLine(subDirectory); // get any sub directories under this directory // by calling this function recursively getSubDirectories(subDirectory); } }
Listing ALL Sub Directories Using C# (Using Recursion) was originally found on Access 2 Learn