Home > Articles > Programming > C#

.NET Reference Guide

Hosted by

Toggle Open Guide Table of ContentsGuide Contents

Close Table of ContentsGuide Contents

Close Table of Contents

Creating a Full Directory Listing

Last updated Mar 14, 2003.

The code above will work fine if all you want is a listing of the files in a single directory. But if you want to list the files in all of the subdirectories you need to visit each subdirectory individually. There are several ways to go about doing such a thing. The solution I prefer is to use a recursive procedure that processes each file in the directory and then calls itself for each of the subdirectories. The effect is a depth-first traversal of the entire directory hierarchy. The code, as you can see below, isn't much different than the single directory listing code that I showed previously.

[C#]

static void FullDirList(DirectoryInfo dir, string searchPattern)
{
  Console.WriteLine("Directory {0}", dir.FullName);
  // list the files
  foreach (FileInfo f in dir.GetFiles(searchPattern))
  {
    Console.WriteLine("File {0}", f.FullName);
  }
  // process each directory
  foreach (DirectoryInfo d in dir.GetDirectories())
  {
    FullDirList(d, searchPattern);
  }
}

[Visual Basic]

Sub FullDirList(ByVal dir As DirectoryInfo, ByVal searchPattern As String)
  Console.WriteLine("Directory {0}", dir.FullName)
  ' list the files
  Dim f As FileInfo
  For Each f In dir.GetFiles(searchPattern)
    Console.WriteLine("File {0}", f.FullName)
  Next

  ' process each directory
  Dim d As DirectoryInfo
  For Each d In dir.GetDirectories()
    FullDirList(d, searchPattern)
  Next
End Sub

With just a little bit of work, you can wrap that FullDirList method up in a class method that calls a supplied delegate for each directory and file that it encounters during the search, giving you a generalized directory enumeration method. It comes in quite handy if you're writing code that has to work with the file system.