Geeks With Blogs
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)
          files.Add(fileName);
 
     // Iterate through all directories
     string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
     foreach(string subdirectory in subdirectoryEntries)
          files.AddRange(BuildFileList(subdirectory));

     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


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

# re: .NET Recursive Functions - Recurse through Files and Directories
Requesting Gravatar...
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
Requesting Gravatar...
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

# re: .NET Recursive Functions - Recurse through Files and Directories
Requesting Gravatar...
Woops! Sorry about that, that's what heppens when I don't finish copying/pasting...
Left by Matthew Podwysocki on Dec 24, 2007 1:35 PM

Your comment:
 (will show your gravatar)


Copyright © Matthew Podwysocki | Powered by: GeeksWithBlogs.net