I've written a function to recurse a folder structure, but it's not working as intended. The intended behavior is to return the files of the root folder passed, then go into the first folder, return those files, then go into the first subfolder of the first folder and list those files, etc, etc.
Instead, I've managed to get it to return all the Level 1 folders first, then all the Level 2 folders then all the Level 3 etc etc. I can see what is wrong but I'm not sure how to resolve it.
How can I rewrite this to have my expected course of action?
static IEnumerable<string> recurseFolder(String Folder)
{
if (Directory.Exists(Folder))
{
string[] files = null;
string[] dirs = null;
try { files = Directory.GetFiles(Folder); } catch (Exception) { }
if (files != null)
{
foreach (var item in files)
{
yield return item;
}
}
try { dirs = Directory.GetDirectories(Folder); } catch (Exception) { }
if (dirs != null)
{
foreach (var dir in dirs)
{
foreach (var item in recurseFolder(dir))
{
yield return item;
}
}
}
}
}
Update 1 This may be an inconsistency with dotnet core on Linux and Windows, this is my results on Windows and what I was expecting it would look like.
d:\root\Folder A\File 1.txt
d:\root\Folder A\Folder B\File 2.txt
d:\root\Folder A\Folder B\Folder C\File 3.txt
d:\root\Folder A\Folder B\Folder D\File 4.txt
d:\root\Folder A\Folder E\File 5.txt
d:\root\Folder A\Folder F\File 6.txt
d:\root\Folder A\Folder F\Folder G\File 7.txt
d:\root\Folder H\File 8.txt
d:\root\Folder H\Folder I\File 9.txt
d:\root\Folder H\Folder I\Folder J\File 10.txt
d:\root\Folder H\Folder I\Folder K\File 11.txt
d:\root\Folder H\Folder L\File 12.txt
d:\root\Folder M\File 13.txt
This is my results on Linux
/home/x/Root/Folder A/File 1.txt
/home/x/Root/Folder A/Folder E/File 5.txt
/home/x/Root/Folder A/Folder B/File 2.txt
/home/x/Root/Folder A/Folder B/Folder D/File 4.txt
/home/x/Root/Folder A/Folder B/Folder C/File 3.txt
/home/x/Root/Folder A/Folder F/File 6.txt
/home/x/Root/Folder A/Folder F/Folder G/File 7.txt
/home/x/Root/Folder H/File 8.txt
/home/x/Root/Folder H/Folder I/File 9.txt
/home/x/Root/Folder H/Folder I/Folder K/File 11.txt
/home/x/Root/Folder H/Folder I/Folder J/File 10.txt
/home/x/Root/Folder H/Folder L/File 12.txt
/home/x/Root/Folder M/File 13.txt
Maybe my code is working but I just need to manually sort the directories into alphabetical order, I wonder if linux is returning them in created or modified date order.