获取文件夹中具有特定扩展名的第一个文件
Get the first file with specific extension in a folder
我的 WinForms 应用程序使用文件系统来保存其数据,我从具有唯一扩展名(我创建的)的文件读取和写入。
我想确保我的应用程序始终可以找到该文件,即使它已重命名或移动到子目录。
我看到了 Directory.GetFiles(…)
函数,但它获取 所有 具有扩展名的文件,这意味着即使找到文件后它也会继续搜索。
我的问题是:是否有更高效的方式来搜索这个文件?
提前致谢
是的,有。如您所说,GetFiles
将使用搜索过滤器获取所有文件,然后 return。你不想要那个,你想要 EnumerateFiles
而不是:
An enumerable collection of the full names (including paths) for the files in the directory specified by path and that match the specified search pattern and option.
所以,你基本上想要:
var file = Directory.EnumerateFiles(yourCurrentParameters)
.FirstOrDefault();
一旦找到第一个匹配项,LINQ 就会return。
我的 WinForms 应用程序使用文件系统来保存其数据,我从具有唯一扩展名(我创建的)的文件读取和写入。
我想确保我的应用程序始终可以找到该文件,即使它已重命名或移动到子目录。
我看到了 Directory.GetFiles(…)
函数,但它获取 所有 具有扩展名的文件,这意味着即使找到文件后它也会继续搜索。
我的问题是:是否有更高效的方式来搜索这个文件?
提前致谢
是的,有。如您所说,GetFiles
将使用搜索过滤器获取所有文件,然后 return。你不想要那个,你想要 EnumerateFiles
而不是:
An enumerable collection of the full names (including paths) for the files in the directory specified by path and that match the specified search pattern and option.
所以,你基本上想要:
var file = Directory.EnumerateFiles(yourCurrentParameters)
.FirstOrDefault();
一旦找到第一个匹配项,LINQ 就会return。