如何检查目录或其任何子目录中是否存在特定文件

在C#中,如何检查目录或其任何子目录中是否存在特定文件?

System.IO.File.Exists似乎只接受一个没有重载的单个参数来搜索子目录。

我可以使用SearchOption.AllDirectories重载LINQ和System.IO.Directory.GetFiles ,但这看起来有点沉重。

var MyList = from f in Directory.GetFiles(tempScanStorage, "foo.txt", SearchOption.AllDirectories) where System.IO.Path.GetFileName(f).ToUpper().Contains(foo) select f; foreach (var x in MyList) { returnVal = x.ToString(); } 

如果你正在寻找一个特定的文件名,使用*.*确实很重要。 试试这个:

 var file = Directory.GetFiles(tempScanStorage, foo, SearchOption.AllDirectories) .FirstOrDefault(); if (file == null) { // Handle the file not being found } else { // The file variable has the *first* occurrence of that filename } 

请注意,这不是您当前的查询所做的 – 因为您的当前查询会找到“xbary.txt”,如果您的foo只是bar 。 我不知道这是否有意。

如果你想知道多个匹配,你当然不应该使用FirstOrDefault() 。 目前尚不清楚你正在尝试做什么,这使得很难给出更具体的建议。

请注意,在.NET 4中还有Directory.EnumerateFiles ,它们可能会或可能不会更好地为您执行。 我非常怀疑当你搜索特定文件(而不是目录和子目录中的所有文件)时它会有所作为,但至少值得了解它。 编辑:如评论中所述, 如果您没有权限查看目录中的所有文件 ,它可能会有所不同 。

另一种方法是自己编写搜索function,其中一个应该可以工作:

  private bool FileExists(string rootpath, string filename) { if(File.Exists(Path.Combine(rootpath, filename))) return true; foreach(string subDir in Directory.GetDirectories(rootpath, "*", SearchOption.AllDirectories)) { if(File.Exists(Path.Combine(subDir, filename))) return true; } return false; } private bool FileExistsRecursive(string rootPath, string filename) { if(File.Exists(Path.Combine(rootPath, filename))) return true; foreach (string subDir in Directory.GetDirectories(rootPath)) { return FileExistsRecursive(subDir, filename); } return false; } 

第一种方法仍然提取所有目录名称,并且当有许多子目录但文件接近顶部时会慢一些。

第二个是递归的,在“最坏情况”场景中会更慢,但是当有许多嵌套子目录但文件位于顶级目录时会更快。

要检查任何特定目录中存在的文件,请执行以下操作:“UploadedFiles”是文件夹的名称。

File.Exists(使用Server.Mappath( “UPLOADEDFILES /”))

享受编码

它是对文件系统的递归搜索 。 您在CodeProject中有一些function示例:

  • 简单文件搜索类(按惯例)
  • 使用事件使用递归扫描目录(作者Jan Schreuder)

这是一个递归搜索函数,一旦找到您指定的文件就会中断。 请注意,参数应指定为fileName(例如testdb.bak)和目录(例如c:\ test)。

请注意,如果在具有大量子目录和文件的目录中执行此操作,这可能会非常慢。

 private static bool CheckIfFileExists(string fileName, string directory) { var exists = false; var fileNameToCheck = Path.Combine(directory, fileName); if (Directory.Exists(directory)) { //check directory for file exists = Directory.GetFiles(directory).Any(x => x.Equals(fileNameToCheck, StringComparison.OrdinalIgnoreCase)); //check subdirectories for file if (!exists) { foreach (var dir in Directory.GetDirectories(directory)) { exists = CheckIfFileExists(fileName, dir); if (exists) break; } } } return exists; }