
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Obtaining the Directory Tree
|
713
12.14 Obtaining the Directory Tree
Problem
You need to get a directory tree, potentially including filenames, extending from any
point in the directory hierarchy. In addition, each directory or file returned must be
in the form of an object encapsulating that item. This will allow you to perform oper-
ations on the returned objects, such as deleting the file, renaming the file, or examin-
ing/changing its attributes. Finally, you potentially need the ability to search for a
specific subset of these items based on a pattern, such as finding only files with the
.pdb extension.
Solution
By placing a call to the GetFileSystemInfos instance method in a recursive method,
you can iterate down the directory hierarchy from any starting point and get all files
and directories:
public static void GetAllDirFilesRecurse(string dir)
{
DirectoryInfo mainDir = new DirectoryInfo(dir);
FileSystemInfo[] items = mainDir.GetFileSystemInfos( );
foreach (FileSystemInfo item in items)
{
if (item is DirectoryInfo)
{
Console.WriteLine("DIRECTORY: " + ((DirectoryInfo)item).FullName);
GetAllDirFilesRecurse(((DirectoryInfo)item).FullName);
}
if (item is FileInfo)
{
Console.WriteLine("FILE: " + ((FileInfo)item).FullName);
}
else
{
Console.WriteLine("Unknown");
}
}
}
It isn’t necessarily ...