I’m trying to locate a file in a subdirectory of a specified folder (Let’s call it MyFolder) and save the subdirectory to a string variable to be used elsewhere. The problem is, that there may be multiple subdirectories in that specified folder, and each subdirectory may contain subdirectories of their own. Only one of said subdirectories in the tree under the MyFolder has the file I’m looking for.
In the example below, it could be in either of (possibly more, but for this example) two locations, but NEVER both.
-Root
--/MyFolder
---/a
-----/aa
-------------/blah.txt (or if not here, it may be...)
---/b
-------/blah.txt (...right here, possibly)
I’m trying to locate blah.txt, of course.
I’ve made a recursive foreach loop as seen below, but it will only return the sub-directory if the file is found in the very first level of sub-directories (/a, or /b). If the file is in /aa or /bb or deeper (root/a/aa/aaa, for example), it returns NULL every time. I’ve spent hours upon hours trying to fix this by slowly stepping through the debugger and watching the locals window closely, but I can’t seem to figure out what’s wrong. It does find the file and stores the correct sub-directory path while in the second foreach loop, but then, for some reason, it starts looping backwards (showing the previous directories until it hits the return "Null";). This does not happen if the file is found within the first level of sub-directories, Only if it finds it within the second level or deeper.
class Program
{
static string dir = @"C:\MyFolder\";
static void Main(string[] args)
{
Console.WriteLine(GetDirectory(dir));
Console.ReadKey();
}
static string GetDirectory(string dir)
{
foreach (string dName in Directory.GetDirectories(dir))
{
foreach (string fName in Directory.GetFiles(dName, "blah.txt"))
{
return dName;
}
GetDirectory(dName);
}
return "NULL";
}
}
The only way I’ve seen anything like this work is if you’re not trying to save the path as a string able to be used elsewhere (possibly even by other functions), but to have it displayed immediately as a void return type, such as in the console (By changing the return to "Console.WriteLine(dName)" and modifying the function call appropriately).
I’m very new to C#, my only coding experience previously has been in JavaScript and AutoHotkey, so my knowledge on languages such as this is still extremely limited, and all I have is a C# beginners guide book I’ve read through and the Internet… and I’ve searched through both valiantly to no avail for this specific issue.. so as it were, any help or pointers are greatly appreciated!
Why no tuse the recursive search built in?
Something like
Have a look at Directory.GetFiles Method (String, String, SearchOption) and SearchOption Enumeration
Or even DirectoryInfo.
Something like