Recursive Retrieval of Directory Structure in C#

This code snippet will retrive/enlists all files and folders in Directory and sub directories in Recursive traversal. See the Code Snippet below.

C#48 lines
using System;
using System.IO;
namespace ConsoleAppDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //List all the directories and files in Drive G:
            GetDirStructure(@"G:");
        }
        #region GetDirStructure
        /// <summary>
        /// Method to recursively write out a directory structure
        /// </summary>
        /// <param name="path">Directory to start at</param>
        public static void GetDirStructure(string path)
        {
            try
            {
                //retrives directory info
                DirectoryInfo dir = new DirectoryInfo(path);
                //get all sub directories of the main directory
                DirectoryInfo[] subDirs = dir.GetDirectories();
                //gets all files in the Parent directory( if any)
                FileInfo[] files = dir.GetFiles();
                foreach(FileInfo fi in files)
                {
                    Console.WriteLine("--> " + fi.FullName.ToString());
                }
                //if subdirectories are available
                if (subDirs != null)
                {
                    foreach (DirectoryInfo sd in subDirs)
                    {
                        //Recursive Call To Same method to enlist sub directory contents
                        GetDirStructure(path + @"\" + sd.Name);
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }
#endregion
    }
}

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

1 comment

  1. […] This post was mentioned on Twitter by Nithin Mohan T K, Nithin Mohan T K. Nithin Mohan T K said: NitRiX posts:- Recursive Retrieval of Directory Structure in C#: This code snippet will retrive/enlists … http://bit.ly/a16D1T :Follow Me […]

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.