As you saw in a previous example, you can easily get a list of files within a Directory/Folder using the Directory helper object that is provided to you in C#. In this example, we will look at using a different helper method to get a list of sub-directories.
You will need to use the System.IO library to have access to the Directory helper object, and its methods.
However, there are a lot of helper methods within that Directory object. For example, you can use the Directory.GetDirectories method to get a list of sub directories.
static void getSubDirectories(string workingDirectory) { // get a list of the sub directories and put into an array string[] subDirectories = Directory.GetDirectories(workingDirectory); foreach (string subDirectory in subDirectories) { // go through each element of the array with the loop // print out each directory to the console Console.WriteLine(subDirectory); } }
As you look at the above example, you can see that you are using an array to store the list of directory names. As a matter of form, I use a plural form of a name for variables that are arrays, this is because they hold multiple elements.
You then can see the use of a foreach loop to go through each individual element of the array. A variable, the singular subDirectory, holds the name for a single sub-directory element.
A sample video has been created where you can see this in action:
Get a List of Sub Directories (Folders) From a Directory Using C# was originally found on Access 2 Learn