Search for a File or Directory

9/25/2010 3:18:07 PM
Problem : You need to find a file or directory by name, possibly with wildcards.

The DirectoryInfo object contains many useful functions, among them the ability to search the file system for files and folders containing a search pattern. The search pattern can contain wildcards, just as if you were using the command prompt.

Listing 1 provides a simple example that searches a directory tree for any file or directory that matches the input pattern.

Listing 1. Searching for a File or Directory
using System;
using System.Collections.Generic;
using System.IO;

namespace Find
class Program
static bool _folderOnly = false;
static string _startFolder;
static string _searchTerm;

static void Main(string[] args)
if (!ParseArgs(args))
Console.WriteLine("Searching {0} for \"{1}\" {2}",
_startFolder, _searchTerm,
_folderOnly ? "(folders only)" : "");

private static void DoSearch()
DirectoryInfo di = new DirectoryInfo(_startFolder);
DirectoryInfo[] directories = di.GetDirectories(_searchTerm,
int numResults = directories.Length;
if (!_folderOnly)
FileInfo[] files = di.GetFiles(
numResults += files.Length;

Console.WriteLine("{0:N0} results found", numResults);

private static void PrintSearchResults(
DirectoryInfo[] directories)
foreach(DirectoryInfo di in directories)
di.Name, di.Parent.FullName, "D");

private static void PrintSearchResults(FileInfo[] files)
foreach(FileInfo fi in files)
fi.Name, fi.DirectoryName, "F");

static void PrintUsage()
"Usage: Find [-directory] SearchTerm StartFolder");
Console.WriteLine("Ex: Find -directory code D:\\Projects");
Console.WriteLine("* wildcards are accepted");

static bool ParseArgs(string[] args)
if (args.Length < 2)
return false;
if (string.Compare(args[0], "-directory") == 0)
_folderOnly = true;
if (args.Length < 3)
return false;
_startFolder = args[args.Length - 1];
_searchTerm = args[args.Length - 2];
return true;

Here’s the program output (your results will likely vary):

D:\code\ch11\Find\bin\Debug>Find *media* "c:\Program Files" > temp.txt
Searching c:\Program Files for "*media*"
Windows Media Player c:\Program Files D
VideoMediaHandler.dll c:\Program Files\Movie Maker F
VideoMediaHandler.dll.mui c:\Program Files\Movie Maker\en-US F
3 results found


You may get an “access denied” error while running this program when the search runs across a folder you don’t have permission to access. One way to handle this is to change the search options to SearchOption.TopDirectoryOnly, track the subdirectories in a stack, and perform the recursive search yourself, handling the possible exceptions along the way.

Top 10
HP Spectre XT Touchsmart Review - Everything Is Fine Except Battery Life (Part 2)
HP Spectre XT Touchsmart Review - Everything Is Fine Except Battery Life (Part 1)
Lenovo Thinkpad Carbon Touch Ultrabook Review (Part 3)
Lenovo Thinkpad Carbon Touch Ultrabook Review (Part 2)
Lenovo Thinkpad Carbon Touch Ultrabook Review (Part 1)
Blackberry 10 OS (Part 3)
Blackberry 10 OS (Part 2)
Blackberry 10 OS (Part 1)
How To Keep High-End Speakers In Good Conditions
How To Use TV As An Audio Converter
Most View
Windows Small Business Server 2011 : Managing User Roles
Canon IXUS 510 HS
Review: Nikon D4 – The master of the dark arts (Part 2)
Sharepoint 2007: Use the My Links to Manage Your Links
Every Cloud...(Part 2) - Mobility & Portability
Searching for Google’s future (Part 1) - Taking the tablets
Dell Inspiron 17R Special Edition - Battery Is A Disappointment
10 Valuable TVs For Your Living Room
Silverlight Recipes : Creating Silverlight Using Ruby, Python, or JScript
Build A Home Theatre PC (Part 2)
The Library In Your Pocket (Part 2) - iOS – iPad, Android – Kobo Vox, Kindle Fire, Binatone ReadMe, Google Nexus 7
Samsung 830
Windows 9 : What to expect - 32-bit support , WinRT & XNA
Programming with DirectX : View Transformations
Securing Your Silverlight Application
Programming the Mobile Web : Mobilizing WordPress and Other CMSs
Aerocool Silent Master Blue
Getting Started with Device Manager
Calendar Plus - Simple And Friendly
Transact-SQL in SQL Server 2008 : New date and time Data Types and Functions