You need to process multiple files based on a filter expression (such as *.dll or mysheet20??.xls).
Use the overloaded version of the System.IO.DirectoryInfo.GetFiles method that accepts a filter expression and returns an array of FileInfo objects.
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. You can use a similar technique to retrieve directories that match a specified search pattern by using the overloaded DirectoryInfo.GetDirectories method.
For example, the following code retrieves the names of all the files in a specified directory that match a specified filter string. The directory and filter expression are submitted as command-line arguments. The code then iterates through the retrieved FileInfo collection of matching files and displays the name and size of each one.
using System; using System.IO; public class WildcardTest { private static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine( "USAGE: WildcardTest [directory] [filterExpression]"); return; } DirectoryInfo dir = new DirectoryInfo(args[0]); FileInfo[] files = dir.GetFiles(args[1]); // Display the name of all the files. foreach (FileInfo file in files) { Console.Write("Name: " + file.Name + " "); Console.WriteLine("Size: " + file.Length.ToString()); } Console.ReadLine(); } }
If you want to search subdirectories, you'll need to add your own recursion. Several of the recipes in this chapter demonstrate recursive file processing logic, including recipes 9.3 and 9.4.