Debra Sath
Debra Sath

Reputation: 13

Recursive searching directories with root directory in C#

How do I recursively loop through directories without missing the root directory's files?

I have the following function that recursively searches through all the files in a directory, but it doesn't list the files in the root directory.

public static void ShowFiles(string dirpath)
{
    try
    {
        foreach (string d in Directory.GetDirectories(dirpath))
        {
            foreach (string f in Directory.GetFiles(d))
            {
                Console.WriteLine(f);
            }
            ShowFiles(d);
        }
    }

Can anyone guide me on how I can modify this to list the files in the root directory too?

Upvotes: 1

Views: 97

Answers (2)

Kilazur
Kilazur

Reputation: 3188

Don't forget to catch your try.

First, enumerate the files in the current directory, then repeat the method for its child directories.

public static void ShowFiles(string dirpath)
{
    Console.WriteLine(String.Format("Files in {0}:", dirpath));
    try
    {
        foreach (string f in Directory.GetFiles(dirpath))
        {
            Console.WriteLine('\t' + f);
        }

        foreach (string d in Directory.GetDirectories(dirpath))
        {
            ShowFiles(d);
        }
    }
    catch (Exception e)
    {
        // do something with e
    }
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Move the code that lists the files to the top level, i.e. Outside the loop that processes directories recursively.

foreach (string f in Directory.GetFiles(dirpath)) {
    Console.WriteLine(f);
}
foreach (string d in Directory.GetDirectories(dirpath)) {
     ShowFiles(d);
}

Upvotes: 2

Related Questions