返回不杀死递归函数

0 .net c# recursion return function

我有一些代码可以在整个计算机中搜索文件,一旦找到,就应该返回该文件。问题出在第二个函数中,递归函数。一旦找到文件,它应该返回,它确实这样做了,但由于某种原因,即使在返回值之后,它仍会继续递归搜索。

我不明白。我仍然认为自己是编程新手,所以如果您看到我做错了什么,请详细解释。

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 "";
}
Run Code Online (Sandbox Code Playgroud)

juh*_*arr 5

您的递归调用忽略了返回值。相反,您应该检查它是否找到了一些东西,以便您可以停止搜索更多子目录。

foreach (string newDirectory in Directory.GetDirectories(dir))
{
    Console.WriteLine("Checked path: " + dir + ".");
    var result = SearchDirectory(newDirectory, fileName);
    if(result != "") return result;
}
Run Code Online (Sandbox Code Playgroud)