简体   繁体   中英

Is it possible to enable yield return on DirectoryInfo.GetFiles?

I'm calling GetFiles and I must return the files found in all nested directories. I'd like to be able to do something with the found files as they get returned. Is it possible to call GetFiles in a way to allow yield return? Or is it necessary to roll my own version of GetFiles that uses yield return.

I was thinking of something like DirectoryInfo("MyDir").GetFiles("*.txt",SearchOptions.All).ForEach(dostuff)

where dostuff is a delegate

Yes, DirectoryInfo.EnumerateFiles returns a lazy-loaded IEnumerable

Documentation

Your line would be:

(new DirectoryInfo("MyDir")).EnumerateFiles("*.txt",SearchOptions.All).ForEach(dostuff)

Just use DirectoryInfo("MyDir").EnumerateFiles() , it already does a yield return for you.

It is available from .NET 4 and returns an IEnumerable<FileInfo> .

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