12.7. 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 calling the GetFileSystemInfos instance method, you can retrieve all of the files and directories down the directory hierarchy from any starting point as an enumerable list:
public static IEnumerable<FileSystemInfo> GetAllFilesAndDirectories(string dir)
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
Stack<FileSystemInfo> stack = new Stack<FileSystemInfo>();
stack.Push(dirInfo);
while (dirInfo != null || stack.Count > 0)
{
FileSystemInfo fileSystemInfo = stack.Pop();
DirectoryInfo subDirectoryInfo = fileSystemInfo as DirectoryInfo;
if (subDirectoryInfo != null)
{
yield return subDirectoryInfo;
foreach (FileSystemInfo fsi in subDirectoryInfo.GetFileSystemInfos())
stack.Push(fsi);
dirInfo = subDirectoryInfo;
}
else
{
yield return fileSystemInfo;
dirInfo = null;
}
}
}To display the results of the file and directory retrieval, use the following query:
public static void DisplayAllFilesAndDirectories(string ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access