Process Files Recursively

Problem

You need to perform a task with all the files in the current directory and any subdirectories.

Solution

Use the DirectoryInfo.GetFiles method to retrieve a list of files in a directory, and use recursion to walk through all subdirectories.

Discussion

Both the Directory and DirectoryInfo classes provide a GetFiles method, which retrieves files in the current directory. They also expose a GetDirectories method, which retrieves a list of subdirectories. To process a tree of directories, you can call the GetDirectories method recursively, working your way down the directory structure.

The FileSearcher class that follows shows how you can use this technique to perform a recursive search. The SearchDirectory routine adds ...

Get Microsoft® Visual Basic® .NET Programmer's 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.