C# Recursive File Iteration

C# Code Snippets Recursive File Iteration
Share:

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);
            }
        }
    }
}

Result

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger