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

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

Subscribe to get the latest posts sent to your email.

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.