
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
714
|
Chapter 12: Filesystem I/O
{
GetAllFilesInPatternRecurse(((DirectoryInfo)item).FullName);
}
if (item is FileInfo)
{
FileInfo fileInfo = item as FileInfo;
if(fileInfo.Extension.ToUpper( ).CompareTo(".PDB")==0)
Console.WriteLine("FILE: " + (fileInfo.FullName));
}
}
}
Discussion
To obtain a tree representation of a directory and the files it contains, you can use a
simple recursive method. This recursive method first creates a
DirectoryInfo object
that begins in the directory with which you wish to start creating a hierarchy; in the
first code example in the Solution section, this directory is represented by the
mainDir
object.
Next, it can call the
GetFileSystemInfos method on the mainDir object to obtain both
DirectoryInfo and FileInfo objects representing the files and directories in that ini-
tial folder. Alternatively, it could call both the
GetFiles and GetDirectories methods
on the
mainDir object; the latter two methods return string arrays containing the
paths and names of files and directories.
Simply calling the
GetFileSystemInfos method is easy enough, but you need to cast
the returned
FileSystemInfo objects to their correct subtype, which is either a
DirectoryInfo or a FileInfo object. Once cast to the correct type, you can perform
operations on that object.
The final step is