11.13. Searching for Directories or FilesUsing Wildcards

Problem

You are attempting to find one or more specific files or directories that might or might not exist within the current filesystem. The search might need to use wildcard characters in order to widen the search; for example, searching for all user mode dump files in a filesystem. 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, the following method retrieves a string array containing the names of all files and subdirectories in a particular directory, then displays them:

public void DisplayFilesDirs(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. For example, the following method retrieves a string array containing the names of all subdirectories in a particular directory, then displays them:

public void DisplayDirs(string path) { string[] items = Directory.GetDirectories(path); foreach (string item ...

Get C# 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.