0

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

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

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

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

但事实并非如此。

4

2 回答 2

4

你想做的事情可以用这个轻松完成

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();
}
于 2012-07-19T18:07:38.767 回答
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;

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

于 2012-07-19T17:59:33.470 回答