12.6. Searching for Directories or Files Using Wildcards

Problem

You are attempting to find one or more specific files or directories that might or might not exist within the current file system. The search might need to use wildcard characters in order to widen the search, for example, searching for all usermode dump files in a file system. These files have a .dmp extension.

Solution

There are several methods of obtaining this information. The first three methods return a string array containing the full path of each item. The next three methods return an object that encapsulates a directory, a file, or both.

The static GetFileSystemEntries method on the Directory class returns a string array containing the names of all files and directories within a single directory, for example:

	public static void DisplayFilesAndSubDirectories(string path)
	{
	    string[] items = Directory.GetFileSystemEntries(path);
	    foreach (string item in items)
	    {
	        Console.WriteLine(item);
	    }
	}

The static GetDirectories method on the Directory class returns a string array containing the names of all directories within a single directory. The following method, DisplayDirs, shows how you might use it:

	public static void DisplaySubDirectories(string path)
	{
	    string[] items = Directory.GetDirectories(path);
	    foreach (string item in items)
	    {
	        Console.WriteLine(item);
	    }
	}

The static GetFiles method on the Directory class returns a string array containing the names of all files within a single directory. The following method is very ...

Get C# 3.0 Cookbook, 3rd Edition 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.