我想检查我传递的目录中的文件是否具有特定的扩展名。
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 的文件,我也会得到错误的结果——有时我得到正确的结果,有时我得到错误的结果)。
如果我逐步浏览它,看起来我正在查看目录并递归地进入它们并浏览文件......
但事实并非如此。