I was looking for a way to loop into all the files and folders in a given path and I stumbled into this: get tree structure of a directory with its subfolders and files using C#.net in windows application
I was fascinated by Xiaoy312 repost. So I took their code and modified it to serve my intended purpose, which is returning a list of all files' paths in a given path:
using System;
using System.Collections.Generic;
using System.IO;
class Whatever
{
static List<string> filePaths = new List<string>();
static void Main()
{
string path = "some folder path";
DirectoryInfo directoryInfo = new DirectoryInfo(path);
IEnumerable<HierarchicalItem> items = SearchDirectory(directoryInfo, 0);
foreach (var item in items) { } // my query is about this line.
PrintList(filePaths);
Console.Read();
}
static void PrintList(List<string> list)
{
foreach(string path in list)
{
Console.WriteLine(path);
}
}
public static IEnumerable<HierarchicalItem> SearchDirectory(DirectoryInfo directory, int deep = 0)
{
yield return new HierarchicalItem(directory.Name, deep);
foreach (DirectoryInfo subdirectory in directory.GetDirectories())
{
foreach (HierarchicalItem item in SearchDirectory(subdirectory, deep + 1))
{
yield return item;
}
}
foreach (var file in directory.GetFiles())
{
filePaths.Add(file.FullName);
yield return new HierarchicalItem(file.Name + file.Extension, deep + 1);
}
}
}
Now I know the general theme of recursiveness and how the function calls itself, etc. But while I was testing the code by trail an error, I noticed that it doesn't matter whether that last foreach in the "Main" method is empty or not, also, when that foreach is removed, filePaths are not filled anymore.
My Questions:
- So why that last foreach in "Main" method fills the list even if it is empty? And why when it is removed, filling the list fails?
- Can someone mention the steps of the recursiveness cycle, such as
- SearchDirectory called,
- the Empty foreach iterates the first item,
- SearchDirectory returns new HierarchicalItem of the path folder.
- SearchDirectory loops inside each directory, etc.
I will be grateful for that, especially Question 2. Thank you very much