[英]Find a file within all possible folders?
I was wondering how I could use c# to find a specific file (example cheese.exe) within all possible directories?我想知道如何使用 c# 在所有可能的目录中查找特定文件(例如 cheese.exe)? And then store the path to the directory it found it in?
然后将路径存储到它找到的目录中?
This code fragment retrieves a list of all logical drives on the machine and then searches all folders on the drive for files that match the filename "Cheese.exe".此代码片段检索机器上所有逻辑驱动器的列表,然后在驱动器上的所有文件夹中搜索与文件名“Cheese.exe”匹配的文件。 Once the loop has completed, the List "files" contains the
循环完成后,列表“文件”包含
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));
}
If you want to know a little more about the mechanics of searching multiple directories, Googling revealed this post .如果你想更多地了解搜索多个目录的机制,谷歌搜索揭示了这篇文章。 It has a good solution and explanation of recursing through directories yourself.
它有一个很好的解决方案和自己通过目录递归的解释。 You can change the filespec in
Directory.GetFiles
to match your search string and probably use it as is.您可以更改
Directory.GetFiles
的文件规范以匹配您的搜索字符串,并可能按原样使用它。
The link is unfortunately dead now, but in a nutshell the solution basically boils down to:不幸的是,该链接现在已经失效,但简而言之,解决方案基本上可以归结为:
string[] files = Directory.GetFiles("C:\\Starting\\Path\\For\\Search\\",
"cheese.exe",
SearchOption.AllDirectories);
Note the filespec (second parameter) accepts wildcards, so you can also search for " .exe" or even " .*" to list all files recursively.请注意 filespec(第二个参数)接受通配符,因此您还可以搜索“ .exe”甚至“ .*”以递归列出所有文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.