Skip to content

Cory Foy

Organizational agility through intersecting business and technology

Menu
  • FASTER Fridays
  • Mapping Mondays
  • Player Embed
  • Search Videos
  • User Dashboard
  • User Videos
  • Video Category
  • Video Form
  • Video Tag
Menu

Printing a directory list, recursively

Posted on July 16, 2005 by Cory Foy

I was in Sam Ash on Friday (trying to pick up one of these) chatting with one of the guys in Pro Audio. He found out I do software development, and said that he had asked over 20 different people how he can get a simple printout of all the files in a directory, including the files in any subdirectories.

I looked around on Google for a bit, and did find one Sourceforge project, and found the command line switch for it (dir /s if interested), but I wanted a more tree view. So I threw together a simple directory traversal printer. Not much to it really, the heart of it is a GetFilesAndDirectoriesRecursive method:

private string GetFilesAndDirectoriesRecursive(DirectoryInfo dir, string prefix)

{

  DirectoryOutput.Text += ".";
  DirectoryOutput.Refresh();
  System.Text.StringBuilder output = new System.Text.StringBuilder();

  output.Append(prefix + "+" + dir.Name + LINE_BREAK);

  DirectoryInfo[] dirs = dir.GetDirectories();

  foreach(DirectoryInfo d in dirs)
  {
    output.Append(GetFilesAndDirectoriesRecursive(d, INDENT_PREFIX + prefix));
  }

  FileInfo[] files = dir.GetFiles();

  foreach(FileInfo file in files)
  {
    output.Append(prefix + INDENT_PREFIX + "-" + file.Name + LINE_BREAK);
  }

  return output.ToString();

}

Anyway, if you need something like this, you can grab it from here, full source included.

(EDIT: A good friend (and awesome developer) Brady Gaster rewrote this using delegates and callbacks. Definately worth checking out.)

© 2025 Cory Foy | Powered by Superbs Personal Blog theme