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 ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.