In this lab, you'll continue to explore recursion. Specifically, you'll develop a small console application that invokes a recursive method that will calculate how many files exist within a specified folder (counting files in subfolders, too, of course).
The lab will have multiple steps, and you should try and perform the lab steps on your own, but certainly click through the how-to links to see step-by-step walkthroughs on how to complete each step.
Here are the steps:
In C#, the package for working with files is System.IO. So to get access to the classes we'll need for this lab, add a "using" clause to the beginning of your program.cs file.
There are two main classes that System.IO provides that we're interested in:
DirectoryInfo contains information about a specific directory/folder; we can use this class to ask it what files it contains (using the GetFiles method) as well as ask it what subfolders it contains (using the GetDirectories method). The constructor for the DirectoryInfo can take in a string parameter specifying what folder the DirectoryInfo should bind itself to. For example:
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Jon A Preston\Documents\Visual Studio 2005\Projects");
will look into that specific folder, and all operations on the object "dir" will work within that folder.
Remember that the @ symbol before a string tells C# not to parse the string for escape sequences (\n \t, etc.), so your \ will be left alone. Leave off the @ symbol outside the string, and the folder won't work properly (unless you double up your \ symbols).
Create a DirectoryInfo object and then invoke the GetFiles method and display the contents/files of the folder of your choice.
Click this how-to to see a step-by-step solution for this part of the lab.
Now that you have some idea of how to work with files and folders, you need to write a method that recursively examines all of the files and subfolders within a folder.
Realize that we can use the GetDirectories method of the DirectoryInfo class to ask for an array representing the subfolders.
The logic of the recursive method is:
Notice that the work to be done at the current level within the recursion is only to count the files at that folder and sum whatever is returned from the recursive calls on the subfolders.
Write this method based upon the above discussion.
Click this how-to to see a step-by-step solution for this part of the lab.
Now create a DirectoryInfo based upon some folder you want (you can even prompt the user) and then invoke the recursive method and print the results.
Click this how-to to see a step-by-step solution for this part of the lab.
Click her to see the finished ZIPed solution.