Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all files in a folder using enumeration

Tags:

c#

I'm trying to list out all files under a given directory by taking sub directories as well into account.I'm using yield so that I could club this with Take where I call this (note that I'm using .NET 3.5).

Below is my code:

IEnumerable<string> Search(string sDir)
{
       foreach (var file in Directory.GetFiles(sDir))
       {
            yield return file;                
       }

       foreach (var directory in Directory.GetDirectories(sDir))
       {
                Search(directory);                
       }
}

I don't know what is going wrong here, but it only returns one file (which is the one under the root directory, and there is only one there as well). Can you please help?

like image 307
Mike Avatar asked May 17 '13 11:05

Mike


1 Answers

You need to yield the results of the recursive search, otherwise you're just throwing its results away:

IEnumerable<string> Search(string sDir)
{
    foreach (var file in Directory.GetFiles(sDir))
    {
        yield return file;                
    }

    foreach (var directory in Directory.GetDirectories(sDir))
    {
        foreach(var file in Search(directory))
            yield return file;
    }
}

Note that if your intent is to simply get a flat list of every file, consider using Directory.GetFiles instead with the option to search all subdirectories. If your intent is to leverage LINQ (or other methods) to apply searching criteria or a limit to the total number of files retrieved, then this is a decent way to go as you'll read directories one at a time and stop once you've fulfilled your criterion.

like image 146
Chris Sinclair Avatar answered Oct 04 '22 02:10

Chris Sinclair