我想知道如何使用C#在所有可能的目录中查找特定文件(例如cheese.exe),然后存储它所在的目录路径?
我想知道如何使用C#在所有可能的目录中查找特定文件(例如cheese.exe),然后存储它所在的目录路径?
这段代码片段检索机器上所有逻辑驱动器的列表,然后在驱动器上搜索与文件名“Cheese.exe”匹配的所有文件夹。一旦循环完成,列表“files”包含了
var files = new List<string>();
//@Stan R. suggested an improvement to handle floppy drives...
//foreach (DriveInfo d in DriveInfo.GetDrives())
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "Cheese.exe", SearchOption.AllDirectories));
}
Directory.GetFiles
中更改文件规范以匹配您的搜索字符串,并可能直接使用它。string[] files = Directory.GetFiles("C:\\Starting\\Path\\For\\Search\\",
"cheese.exe",
SearchOption.AllDirectories);