如何使用DirectoryInfo.GetFiles并在找到第一个匹配项后使其停止? [英] How to use DirectoryInfo.GetFiles and have it stop after finding the first match?

查看:100
本文介绍了如何使用DirectoryInfo.GetFiles并在找到第一个匹配项后使其停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要搜索目录/子目录来查找文件,希望它一旦找到就停止.

Need to search the directory/sub-directories to find a file, would prefer it to stop once it has found one.

这是我缺少的DirectoryInfo.GetFiles内置的功能,还是我应该使用其他功能(自行实现的递归搜索)?

Is this a feature built into DirectoryInfo.GetFiles that I am missing, or should I be using something else (self-implemented recursive search)?

推荐答案

使用 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)

这篇关于如何使用DirectoryInfo.GetFiles并在找到第一个匹配项后使其停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆