【问题标题】:Is there a method to finding if a file exist in a directory containing many subfolders? [duplicate]有没有一种方法可以查找包含许多子文件夹的目录中是否存在文件? [复制]
【发布时间】:2019-12-15 12:37:20
【问题描述】:

我正在寻找一种有效的方法来搜索给定目录中是否存在文件。 问题是我不知道包括所有子文件夹的完整路径。我只知道目录的顶级文件夹。 有没有办法在不包括完整路径的情况下搜索整个目录中是否存在文件。

 //I would like to try this below
foreach(var file in files)
{
string filename = file.Name;
bool does_it_exist = File.Exists(C:\\,filename);
Console.WriteLine(does_it_exist);
}

【问题讨论】:

  • 该循环中使用的 files 变量是什么?它是 FileInfo 实例的列表还是数组?
  • 您可以使用Directory.GetFiles()。有一个接受 searchOptions 参数的重载,您可以使用它来告诉它搜索子目录。
  • files 是关于另一个目录的 FileInfo 数组。我正在检查目录中的每个文件是否也在另一个目录中。

标签: c# file system.io.file


【解决方案1】:

试试这个:

string[] matchingFiles = System.IO.Directory.GetFiles(path, "ABC123" );

【讨论】:

  • 不会搜索子文件夹。
  • 试试这个:string[] matchingFiles = System.IO.Directory.GetFiles("c://", "ABC123", SearchOption.AllDirectories); SearchOption.AllDirectories 在所有子目录中搜索。
猜你喜欢
  • 2021-08-14
  • 2023-03-27
  • 2013-02-13
  • 2015-01-03
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
  • 2014-05-10
  • 2015-09-14
相关资源
最近更新 更多