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

发布于 2024-07-30 05:49:43 字数 65 浏览 3 评论 0原文

我想知道如何使用 c# 在所有可能的目录中查找特定文件(例如cheese.exe)? 然后存储它找到的目录的路径?

I was wondering how I could use c# to find a specific file (example cheese.exe) within all possible directories? And then store the path to the directory it found it in?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我一直都在从未离去 2024-08-06 05:49:43

此代码片段检索计算机上所有逻辑驱动器的列表,然后在驱动器上的所有文件夹中搜索与文件名“Cheese.exe”匹配的文件。 循环完成后,列表“文件”包含

     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));
     }

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". 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));
     }
世俗缘 2024-08-06 05:49:43

如果您想更多地了解搜索多个目录的机制,谷歌搜索显示这篇文章 。 它有一个很好的解决方案,并解释了您自己递归目录的情况。 您可以更改 Directory.GetFiles 中的文件规范以匹配您的搜索字符串,并可能按原样使用它。

不幸的是,该链接现在已失效,但简而言之,解决方案基本上可以归结为:

string[] files = Directory.GetFiles("C:\\Starting\\Path\\For\\Search\\",
    "cheese.exe",
    SearchOption.AllDirectories);

注意 filespec(第二个参数)接受通配符,因此您还可以搜索“.exe”甚至“.* " 递归列出所有文件。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文