Geeks With Blogs

News Disclaimer
The views expressed on this weblog are mine and do not necessarily reflect the views of my employer.

All postings are provided "AS IS" with no warranties, and confer no rights.

Blog Moved to http://podwysocki.codebetter.com/ Blog Moved to http://podwysocki.codebetter.com/
One of the things driven home during most computer science courses, at least in my era, was all about linked lists, pointers, hexidecimal calculations, bubble sorts, and last but not least, recursive functions.

If you need a slight introduction to recursion, Wikipedia is a good place to start here.  Anyways, I thought I'd bring that same concept when iterating through and creating a list of all files in a directory and all subdirectories.  It's a fairly simple concept in which you iterate through each file and then move to the next directory.

Below is a code example of how to create a List<string> including all file names under a certain directory including the subdirectories.

public static List<string> BuildFileList(string targetDirectory)
{
// Create list of files
List<string> files = new List<string>();

// Iterate through all files
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)

// Iterate through all directories
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)

return files;
}

As you can see, it's a pretty straightforward approach to adding things to a list.  There are no member variables involved and I'm just adding all my results to my List Generic.

I certainly hope today's CS people still learn the basics like these as they are pretty valuable things!

Posted on Monday, July 3, 2006 2:31 PM Microsoft , .NET , C# | Back to top

Related Posts on Geeks With Blogs Matching Categories

Comments on this post: .NET Recursive Functions - Recurse through Files and Directories

# re: .NET Recursive Functions - Recurse through Files and Directories
Don't forget to RETURN your files list at the end of the method...
Left by Rafe on Aug 20, 2007 9:03 AM

# re: .NET Recursive Functions - Recurse through Files and Directories
Thanks for posting the code. It works great. However, the version that you posted doesn't compile as it's missing "return" statement.
Left by Mark on Dec 23, 2007 4:17 PM