如何在 C# 中检查文件是否位于任何文件夹及其所有子文件夹中

本文关键字:文件夹 于任何 是否 检查 文件 | 更新日期: 2023-09-27 18:34:09

我有这个代码

foreach (syncspec.Attribute attr in attributes)
{
      string fullPath = location + "''" + attr.link;
      if (File.Exists(fullPath))
}

我正在检查一个已知的位置,下面列出了一个示例完整路径

// fullPath = "C:''Users''matt''Desktop''shard''all/file30005"

我想做的是查看所有文件夹和所有文件夹中的任何子文件夹......关于如何实现这一目标的任何想法

如何在 C# 中检查文件是否位于任何文件夹及其所有子文件夹中

System.IO.Directory.GetFiles(location, attr.link, SearchOption.AllDirectories);

通过 MSDN 阅读有关 GetFiles 的更多信息:http://msdn.microsoft.com/en-us/library/ms143316

你的朋友是

DirectoryInfo.GetFiles("filename", SearchOption.AllDirectories);

如本例所示:

DirectoryInfo info = new DirectoryInfo(location);
FileInfo[] results = info.GetFiles(attr.Link, SearchOption.AllDirectories);
foreach(FileInfo fi in results)
    ....

请参阅 MSDN 文档以供参考

您可以按照其他人的建议使用 GetFiles(..) 或使用这样的递归方法(顺便说一句,完全有效的解决方案):

bool FileExists(string path, string filename)
{
  string fullPath = Path.Combine(path, filename);
  return File.Exists(fullPath) && Directory.GetDirectories(path).All(x => FileExists(x, filename));
}

首先不要在路径上使用简单的串联,而是使用 Path.Combine:

string parentDirPath = Path.Combine(location , attr.link);

其次,为了遍历所有子目录,可以使用

目录

.枚举目录

例:

foreach (var dir in  Directory.EnumerateDirectories(parentDirPath))
{
     //do something here
}

这个解决方案有点重,但我使用它的变体,因为它允许您在搜索时捕获任何异常并继续。 如果遇到无权遍历的目录,GetFiles()将完全出错。

检查一下:安全文件枚举