C# Getting Information about your Folders

by CameronM 14. July 2010 10:22

Continuing on our journey converting old VBA code to C#, in this post we’ll revisit getting information about the folders/directories on a system. In .NET parlance, folders on the file system are directories, so from here on in, that’s what we’ll call them.

In the last post we looked at how to retrieve a list of drives on the system, so in this post we’ll create a Console Application to return a list of directories in a specific drive.

Ensure you have added the System.IO namespace to Program.cs.

Code Snippet
  1. using System.IO;

Copy the following code into the Main method. This code will iterate through the directories under C-drive and print the directory name in the console. NOTE: any slashes '\' in the directory path need to be escaped - for exampl, we have C:\\, not C:\.

Code Snippet
  1. // set the root or starting directory
  2. DirectoryInfo dir = new DirectoryInfo("C:\\");
  3.  
  4. // get all the children under the root
  5. DirectoryInfo[] children = dir.GetDirectories();
  6.  
  7. foreach (DirectoryInfo d in children)
  8. {
  9.     Console.WriteLine(d.Name);
  10. }

In the code above we set the starting directory to the C-drive root, but it is important to know that you can set the starting directory to any valid directory on the system, not just drives.

It is possible to continue down the system hierarchy and return the children of each of directory by calling the GetDirectories method on each. Writing a function that recursively calls GetDirectories for each subsequent DirectoryInfo object would effectively traverse the entire directory structure.

Tags:

C#