About
In this post, we will see how to recursively iterate through files and folders in C#.
To recursively iterate through the file system we will first call the getFileNames() method and pass it the path of our directory as an input parameter. The method will first get and then print all the files in the provided directory. After that, it will get all the directories. If there are any the getFileNames() method will call itself for every directory and pass the path as the parameter, else the recursion will stop.
If you want to know more about recursion itself check out this post I made.
Let’s see the code example below.
Code:
using System; using System.IO; namespace RecursiveFileIterator { class Program { static void Main(string[] args) { getFileNames("C:\\Users\\DTPC\\Desktop\\MyDirectory"); Console.ReadLine(); } public static void getFileNames(string path) { //Get files and print their names. var files = Directory.GetFiles(path); foreach (var file in files) { Console.WriteLine(file); } //Get directories. var directories = Directory.GetDirectories(path); //Get the directories and call getFileNames() to get the members of that directory. foreach (var directory in directories) { getFileNames(directory); } } } }