且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用DirectoryInfo.GetFiles并在找到第一个匹配项后使其停止?

更新时间:2022-04-15 21:22:29

使用 DirectoryInfo.EnumerateFiles() 相反,它懒惰地返回文件(而不是GetFiles首先将完整文件列表带入内存)-您可以添加FirstOrDefault()来实现所需的目标:

Use DirectoryInfo.EnumerateFiles() instead which is lazily returning the files (as opposed to GetFiles which is bringing the full file list into memory first) - you can add FirstOrDefault() to achieve what you want:

var firstTextFile = new DirectoryInfo(someDirectory).EnumerateFiles("*.txt")
                                                    .FirstOrDefault();

从MSDN:

EnumerateFiles和GetFiles方法的区别如下: 使用EnumerateFiles,您可以开始枚举 返回整个集合之前的FileInfo对象;当你使用 GetFiles,您必须等待FileInfo对象的整个数组成为 在可以访问数组之前返回.因此,当你 通过处理许多文件和目录,EnumerateFiles可以更多

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of FileInfo objects before the whole collection is returned; when you use GetFiles, you must wait for the whole array of FileInfo objects to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

(DirectoryInfo.EnumerateFiles需要.NET 4.0)

(DirectoryInfo.EnumerateFiles requires .NET 4.0)