DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 11.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 operations on the returned objects, such as deleting the file, renaming the file, or examining/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 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 true that you have to use recursion to retrieve information about all files and directories. The following recursive method uses both the GetFiles and GetDirectories instance methods with pattern matching to obtain a listing of all files with the extension of .pdb that exist in directories that begin with a "Chapter 1":

public void GetAllFilesInPatternRecurse(string Dir)
{
    DirectoryInfo mainDir = new DirectoryInfo(dir);
    FileSystemInfo[] items = mainDir.GetFileSystemInfos("Chapter 1*");
    foreach (FileSystemInfo item in items)
    {
        if (item is DirectoryInfo)
        {
            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 with its respective files, 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. It must then check the pattern for this directory to see whether it should be reported before moving down the directory trees.

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 initial folder. Alternatively, it could call both the GetFiles and GetDirectories methods on the mainDir object; the latter two methods return a string array 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 to add a recursive method call every time you find a DirectoryInfo object. This DirectoryInfo object is then passed as an argument to this same function, making it the starting directory for the new function call. This continues on until every directory under the initial directory has been returned along with its contents.

You will note that the check of the FileSystemInfos in the if statements are not an if-else tree. This is done deliberately so that you catch the files in a directory as you traverse back upwards.

See Also

See the "DirectoryInfo Class," "FileInfo Class," and "FileSystemInfo Class" topics in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section