我有一段代码可以在整个计算机上搜索文件,一旦找到,应该返回该文件。问题出在第二个函数中,即递归函数。找到文件后,它应该返回该文件,但确实如此,但是由于某种原因,即使返回了该值,它也会继续进行递归搜索。
我不明白。我仍然认为自己是编程新手,因此如果您发现我做错了,请详细说明。
public string SearchDirectory(string dir, string fileName)
{
string foundDir = "";
bool fileFound = false;
// Gets all files from directory and creates list of matches to fileName
try
{
foreach (string match in Directory.GetFiles(dir, fileName))
{
// Returns the first found match as a path and breaks loop
Console.WriteLine("Checked path: " + dir + ".");
if (File.Exists(dir + @"\" + fileName))
{
Console.WriteLine("FOUND!!");
fileFound = true;
foundDir = dir;
break;
}
if (fileFound == true)
{
break;
}
}
}
catch
{
Console.WriteLine("Access to path: " + dir + " denied.");
}
// If fileName isn't found in directory, it searches each new directory
// The last directory it will check is the last one in the original directory
if (fileFound == false)
{
try
{
foreach (string newDirectory in Directory.GetDirectories(dir))
{
Console.WriteLine("Checked path: " + dir + ".");
SearchDirectory(newDirectory, fileName);
}
}
catch
{
Console.WriteLine("Access to path: " + dir + " denied.");
}
// fileName does not exist in starting directory
}
else
{
return foundDir;
}
return "";
}
您的递归调用将忽略返回的值。相反,您应该检查它是否找到了某些东西,以便可以停止搜索更多子目录。
foreach (string newDirectory in Directory.GetDirectories(dir))
{
Console.WriteLine("Checked path: " + dir + ".");
var result = SearchDirectory(newDirectory, fileName);
if(result != "") return result;
}
您可以改为这样做:
public string SearchDirectory(string dir, string fileName)
{
return Directory.EnumerateFiles(dir, fileName, SearchOption.AllDirectories).FirstOrDefault() ?? "";
}