简体   繁体   English

在所有可能的文件夹中查找文件?

[英]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.

相关问题 如何在2个不同大小的字符串数组中查找所有可能的字符串组合 - How to Find All Possible String Combinations Within 2 Different Size String Arrays 索引文件和在文件夹中查找文件的最快捷方式? - Indexing files and quickiest way to find a file in folders? 通过交叉检查在两个文件夹中查找新文件 - Find new file in two folders with a cross check 在子文件夹的所有文件夹中搜索指定文件的存在 - Search in all folders of a subfolder for the presence of a specified file C#删除一个文件夹以及该文件夹内的所有文件和文件夹 - C# delete a folder and all files and folders within that folder Exchange Web 服务 (EWS) 在所有文件夹中查找项目 - Exchange Web Services (EWS) FindItems within All Folders 是否可以“一次性完成”读取链接到另一个XML文件中的XML文件? - Is it possible read XML files that are linked to within another XML file “all in one go”? 查找系统中定义的文件夹层次结构中的所有文件 - Find all files in system that are located inside defined hierarchy of folders 查找共享特殊文件夹(虚拟文件夹)中的所有文件 - Find all files in a shared special folder (Virtual Folders) 列出时间跨度内所有可能时间跨度的算法 - Algorithm listing all possible timespans within a timespan
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM