快速检索文件夹和所有子文件夹中的文件名列表 [英] Retrieve a list of filenames in folder and all subfolders quickly

查看:35
本文介绍了快速检索文件夹和所有子文件夹中的文件名列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取所有 Word 文档的列表.*.doc 和 *.docx 存储在基于 Windows 的文件夹中,有许多子文件夹和子子文件夹等...

I need to get a list of all Word Documents. *.doc and *.docx that are stored in a Windows based folder, with many subfolders, and sub sub folders etc...

用 C# 搜索文件 有一个有效的答案,2岁了,10秒搜索1500个文件,(未来可能有10000个以上).我将发布我的代码,它基本上是来自上述链接的副本.有人有更好的解决方案吗?

Searching for a file with C# has an answer that works, it is 2 years old and takes 10 seconds to search through 1500 files, (in the future there may be 10,000 or more). I will post my code which is basically a copy from the above link. Does anyone have a better solution?

DateTime dt = DateTime.Now;
DirectoryInfo dir = new DirectoryInfo(MainFolder);
List<FileInfo> matches = 
          new List<FileInfo>(dir.GetFiles("*.doc*",SearchOption.AllDirectories));
TimeSpan ts = DateTime.Now-dt;
MessageBox.Show(matches.Count + " matches in " + ts.TotalSeconds + " seconds");

推荐答案

您可以使用 Directory.EnumerateFiles 而不是 GetFiles.这具有将文件作为 IEnumerable 返回的优点,这允许您立即开始处理结果集(而不是等待返回整个列表).

You can use Directory.EnumerateFiles instead of GetFiles. This has the advantage of returning the files as an IEnumerable<T>, which allows you to begin your processing of the result set immediately (instead of waiting for the entire list to be returned).

如果您只是计算文件数量或列出所有文件,则可能无济于事.但是,如果您可以对结果进行处理和/或过滤,特别是如果您可以在其他线程中进行任何处理,那么速度会明显加快.

If you're merely counting the number of files or listing all files, it may not help. If, however, you can do your processing and/or filtering of the results, and especially if you can do any of it in other threads, it can be significantly faster.

来自文档:

EnumerateFiles 和 GetFiles 方法的区别如下: 当您使用 EnumerateFiles 时,您可以在返回整个集合之前开始枚举名称集合;使用 GetFiles 时,必须等待整个名称数组返回,然后才能访问该数组.因此,当您处理多个文件和目录时,EnumerateFiles 可以更高效.

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

这篇关于快速检索文件夹和所有子文件夹中的文件名列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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