Posted by: Rhonda | October 28, 2007

Recursive Directory Search

This post is to demonstrate a basic process of scanning directories recursively for files with a specified extension (ie *.txt or *.jpg).

The Directory class in the System.IO namespace is used to accomplish most of the task. The Directory class contains many useful methods. The two methods used are GetDirectories and GetFiles.

GetDirectories – retrieves the names of subdirectories in the specified directory.
GetFiles – retrieves the names of the files in a specified directories.

C# PROGRAM

using System;
using System.IO;

namespace DirTest
{
  class RecursiveSearch
  {
     static void Main()
     {
        //-- Request top-level directory path
        Console.WriteLine("Enter the top-level directory path to search in");
        string dir2search = Console.ReadLine();

        //-- Request the file extension
        Console.WriteLine("Enter the file extension to search for");
        string ext = "*." + Console.ReadLine();

        Console.WriteLine("");
        Console.WriteLine("<<-- Recursive File Listing for {0} in {1} -->>",ext.ToUpper(), dir2search.ToUpper());

        //-- Call method to recursivly search the directory
        DirSearch(dir2search, ext);
     }

     static void DirSearch(string dir2Search1, string ext1)
     {
        //-- If the directory input does not exist, an exception is thrown
        try
        {
            //-- Cycle through directories
            foreach (string d in Directory.GetDirectories(dir2Search1))
            {
                //-- Cycle through files in directory
                foreach (string f in Directory.GetFiles(d, ext1))
                {
                   Console.WriteLine(f);
                }

                //-- Search next directory
                DirSearch(d, ext1);
            }
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
  }
}

RESULTS

Invalid path entered

There are several possible uses for a recursive file search. One that pops into my head would be to search a hard drive for illegal file types or limit the amount of a file type (such as audio or video files).

.


Leave a response

You must be logged in to post a comment.

Categories