I'm trying to find write a recursive method to find a file in given directory. I'm actually a beginner in programming and C#, this my first time writing a recursive method. The method will go through each file and all sub directories to find the file.
This is what I wrote:
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;
}
Now the problem is when I pass currentDirectory
as C:\users\{Enviroment.UserName}\OneDrive\Desktop\TestFolder
, which contains a few more test folders, it works. But when I try to run it in a folder that I want to find the file in, it doesn't return anything. Path to that folder is C:\users\{Enviroment.UserName}\OneDrive\Data\SomeFolder
that folder has some subdirectories and files and also the file A.txt
I even tried:
foreach (string aPath in files)
{
if (aPath.Contains("A.txt"))
{
requiredPath = aPath;
}
}
but it doesn't work. Am I doing something wrong? I don't understand why it works in the test folders and why it doesn't work When I'm trying to run it in a real folder. Again, I'm just a beginner teenage learning programming, this is my first time writing recursive methods so yeah. This is also my first question in this community.