c#递归搜索以检查文件扩展名

时间:2012-07-19 17:53:19

标签: c# file search recursion

我想检查我传递的目录中的文件是否具有特定的扩展名。

 public static bool ProcessDirectory(string targetDirectory)
 {
     // Process the list of files found in the directory.
     string[] fileEntries = System.IO.Directory.GetFiles(targetDirectory);
     foreach (string fileName in fileEntries)
         if (System.IO.Path.GetExtension(fileName).ToLower().Contains(pattern)) 
             return true;

    // Recurse into subdirectories of this directory.
    string[] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory);
    foreach (string subdirectory in subdirectoryEntries)
        return ProcessDirectory(subdirectory);

   return false;
  }   

致电:

bool foundPattern = false;
//recursive search - based on search pattern 
if (System.IO.File.Exists(myDirectory) && System.IO.Path.GetExtension(myDirectory).Contains(pattern))
{
     // This path is a file
     foundPattern = true;
}
else if (System.IO.Directory.Exists(myDirectory))
{
     // This path is a directory
     foundPattern = ProcessDirectory(myDirectory);
}

问题是,我没有得到一些结果(即使有扩展名为.xzz的文件,我也会得到假设,假设我在搜索模式中要求扩展.x - 有时候我会变成现实,有时我会得到错误)。

如果我单步执行它,看起来我正在查看目录并递归地进入它们并浏览文件......

但事实并非如此。

2 个答案:

答案 0 :(得分:3)

使用此

可以轻松完成您想要做的事情
string path = @"C:\temp\";
string extension = "*.txt";
var files = Directory.GetFiles(path, extension);

//or recursivly
var files = Directory.GetFiles(path, extension, SearchOption.AllDirectories);

在你的情况下:

public static bool ProcessDirectory(string startPath, string pattern)
{ 
    return Directory.GetFiles(startPath, pattern, SearchOption.AllDirectories).Any();
}

答案 1 :(得分:2)

我认为您的代码中存在错误:

// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
    return ProcessDirectory(subdirectory);

应该是这样的:

// Recurse into subdirectories of this directory.
string[] subdirectoryEntries = System.IO.Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
    if (ProcessDirectory(subdirectory))
        return true;

否则,您只返回单个子目录的结果。 它与您在函数开头的循环相同。你第一次就做对了。