且构网

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

快速检索文件夹和所有子文件夹中的文件名列表

更新时间:2022-06-07 22:27:54

您可以使用 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.