c# 如何在所有目录中搜索文件?

How to search for files in all directories c#?

我正在尝试编写递归方法来查找给定目录中的文件。我实际上是编程和 C# 的初学者,这是我第一次编写递归方法。该方法将遍历每个文件和所有子目录以查找文件。

这是我写的:

  static string GetPath(string currentDirectory)
    {
        string requiredPath = "";            
                      
        string[] files = Directory.GetFiles(currentDirectory);
        string[] dirs = Directory.GetDirectories(currentDirectory);
                
        foreach (string aPath in files)
        {
            if (aPath.Contains("A.txt"))
            {
                requiredPath = aPath;                    
            }                                
        }

        foreach (string dir in dirs)
        {
            requiredPath = GetPath(dir);
        }
                                     
        return requiredPath;                        
    }

现在的问题是,当我将 currentDirectory 作为 C:\users\{Enviroment.UserName}\OneDrive\Desktop\TestFolder 传递时,它包含更多的测试文件夹,它可以工作。但是当我尝试 运行 它在我想在其中找到文件的文件夹中时,它没有 return 任何东西。该文件夹的路径是 C:\users\{Enviroment.UserName}\OneDrive\Data\SomeFolder 该文件夹有一些子目录和文件以及文件 A.txt

我什至尝试过:

 foreach (string aPath in files)
        {
            if (aPath.Contains("A.txt"))
            {
                requiredPath = aPath;                    
            }                                
        }

但它不起作用。难道我做错了什么?我不明白为什么它在测试文件夹中工作以及为什么当我尝试 运行 它在真实文件夹中时它不起作用。 再一次,我只是一个学习编程的初学者,这是我第一次编写递归方法,是的。这也是我在这个社区的第一个问题。

好的,我找到了解决方案,我只需要在递归时添加一个 if 命令。

        foreach (string dir in dirs)
        {
            requiredPath = GetPath(dir);
            if (requiredPath.Contains("PasswordGenerator.py"))
                return requiredPath;
        }

它没有检查文件是否在 requiredPath 中,它只是继续搜索。

嗯,我把我的方法给爸爸看了,他又给我做了一个更简单的方法。

 static string GetFilePath(string folderToSearch, string fileName)
    {
        if (Directory.GetFiles(folderToSearch).Any(x => x.Contains(fileName)))
            return folderToSearch;
        var folders = Directory.GetDirectories(folderToSearch);
        foreach(var folder in folders)
        {
            var filePath = GetFilePath(folder, fileName);
            if (filePath != null)
                return filePath;
        }
        return null;
    }