Filter Files with Wildcards

Problem

You need to process multiple files based on a filter expression (such as *.txt or rec03??.bin).

Solution

Use the overloaded version of the DirectoryInfo.GetFiles method that accepts a filter expression.

Discussion

The DirectoryInfo and Directory objects both provide a way to search the current directories for files that match a specific filter expression. These search expressions can use the standard ? and * wildcards.

For example, the following code snippet retrieves the names of all the files in the c:\temp directory that have the extension .txt. The code then iterates through the retrieved FileInfo collection of matching files and displays the name and size of each one.

Dim File, Files() As FileInfo ' Check all ...

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.