Search files in C# recursively


I found this piece of code to search a for a file that containing a pattern (extension, part of the name) 


void DirSearch(string dir, string pattern)


{


    try


    {


        foreach (string d in Directory.GetDirectories(dir))


        {


            foreach (string f in Directory.GetFiles(d, pattern))


            {


                Console.WriteLine(“File found: {0}”, f);


            }


            DirSearch(d);


        }


    }


    catch (Exception ex)


    {


        Console.WriteLine(“Something unexpected happened: {0}”, ex);


    }


}


 


I’ve always thought that the recursive algorithms are an easy small and elegant way to solve a problem, I first learned that in college while I was studying some of the “classical” samples of recursive problems, like fractals, the problem of the 8 queens, tree search, and other graph related problems, the-horse-in-the-chess-board (I am not sure of the name), and others


I’ll try to remember some of those problems and try to solve them again using C#


Comments (4)

  1. Or you could use one line:

    Directory.GetFiles(dir, pattern, SearchOptions.AllDirectories);

  2. Osama Khodrog says:

    but when i use this code i have an Exception

    Access to the path 'd:System Volume Information' is denied.

    Thank you

  3. Osama Khodrog says:

    but when i use this code i have an Exception

    Access to the path 'd:System Volume Information' is denied.

    Thank you

  4. Amit Mishra says:

    i want to find weather a files in directory contains the items stored in the list.How can i do that?