简体   繁体   中英

How to recursively list all the files in and get the files “on going”

I'm writing a program that needs to search a directory and all its sub directories for files that have a certain extension. This is going to be used both on a local, and a network drive, so performance is a bit of an issue.

i know i can use this kind of option:

  foreach (string file in Directory.EnumerateFiles(
        path, "*.*", SearchOption.AllDirectories))
    {
        ///
    }

but my folders gonna have a lot of files so i wondered how to imlement this kind of search that return the files "on going" instead on waiting until all the search will finish (something like Queue)

If you mean that your method should return them one by one (assuming you understood EnumerateFiles() does that already). Use yield return:

public IEnumerable<string > Foo(string path)
{
     foreach (string file in Directory.EnumerateFiles(
        path, "*.*", SearchOption.AllDirectories))
     {
         // Add additional logic if you need here
         yield return file;
      }
}

That way, if you run with foreach on your method you'll get each file at a time and you can add additional logic in the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM