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

[code lang=”c-sharp”]

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

[/code]


Discover more from Cloud Distilled ~ Nithin Mohan

Subscribe to get the latest posts sent to your email.

By Nithin Mohan TK

Technology Enthusiast | .NET Specialist | Blogger | Gadget & Hardware Geek

One thought on “Recursive Retrieval of Directory Structure in C#”

Leave a Reply

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.