Simple C# Directory Recursion

Submitted on: 1/1/2015 4:43:00 AM
By: bleh (from psc cd)  
Level: Beginner
User Rating: By 5 Users
Compatibility: C#
Views: 2951
     This shows and explains how to recursivley add all files, folders, and subfolder to an ArrayList.

Simple Directory Recursion

One of the things I liked a lot back when I was a VB programmer was the easy directory recursion using the File System Object, a function I use quite a bit in my applications. It became a bit more complex in Delphi (at least, the way I do it), so since I am now learning C#, I figured it would be wise of me to figure it out yet again. I was surprised about how simple it is in C#.

The Code:

using System.IO;
// This will be our ArrayList that everything is stored in.
ArrayList sFileList = new ArrayList();
private void recurseDirs(string sPath)
	// First we create an instance of DirectoryInfo and point it to the path we passed as a parameter to the function
	DirectoryInfo dirInfo = new DirectoryInfo(sPath); 
	// Next, we are adding all files in the current path to the ArrayList.
	// Now we step through all of the directories in dirInfo, add them to the ArrayList, and then call the function again.
	foreach(DirectoryInfo subDirs in dirInfo.GetDirectories())

Using This Code:

As shown in the code, make sure to add System.IO to your namespaces. To call this function from your code, simply type


In Conculsion:

Obviously, adding everything to an ArrayList is just an example of what to do with the information. I did notice that it will add all temporary, hidden, and system files and folders to the list. There is a workaround for this using FileAttributes, but since I am still a C# beginner, I haven't figured it out yet.

Other 2 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.