gpt4 book ai didi

c# - 使用 C# 搜索文件

转载 作者:太空宇宙 更新时间:2023-11-03 11:47:16 24 4
gpt4 key购买 nike

在 C# 中以编程方式搜索文件的最快方法是什么。我知道文件的相对位置,比如说它的 “abcd\efgh\test.txt”。 我也知道这个文件在我的 E:\驱动器 上。 "abcd"是 E:\盘中某个目录的子目录。

谢谢

最佳答案

因为您知道要搜索的根目录和文件名的字符串模式,您可以使用根目录创建一个 DirectoryInfo:

DirectoryInfo dir = new DirectoryInfo(@"E:\");

然后调用 GetFiles() 获取所有匹配项。传递 SearchOption.AllDirectories 将确保搜索是递归的。

List<FileInfo> matches = 
new List<FileInfo>(dir.GetFiles(partialFilename,
SearchOption.AllDirectories));

或者如果您知道部分路径(而不是文件名):

List<DirectoryInfo> matches =
new List<DirectoryInfo>(dir.GetDirectories(partialDirectoryName,
SearchOption.AllDirectories));

然后您可以从那里导航到该文件。

关于c# - 使用 C# 搜索文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3102786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com