Xaisoft
Xaisoft

Reputation: 46651

Is it possible to speed this recursive directory method up?

I am listing all directories in a console app, but it takes forever, more than 10+ minutes (just assuming here, it probably took more than 10 minutes), I know there are a ton of directories, but is 10+ minutes too long to begin with?

class Program
    {
        static void Main(string[] args)
        {
            DirSearch(@"c:\");

            Console.ReadKey();
        }

        static void DirSearch(string sDir)
        {
            try
            {
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    Console.WriteLine(d);
                    DirSearch(d);
                }
            }
            catch (System.Exception excpt)
            {
                Console.WriteLine(excpt.Message);
            }
        }
    }

Upvotes: 2

Views: 142

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160992

Yes - don't make it recursive manually. This is built in, you can use SearchOption.AllDirectories to include all subdirectories in your search:

foreach (string d in Directory.GetDirectories(sDir, "*.*", SearchOption.AllDirectories))
{
    Console.WriteLine(d);
}

Or alternatively use Directory.EnumerateDirectories which yields directory names as it finds them instead of putting all of them in an array first:

foreach (string d in Directory.EnumerateDirectories(sDir, "*.*", SearchOption.AllDirectories))
{
    Console.WriteLine(d);
}

Upvotes: 10

Related Questions