How to build a JSON tree of a given directory in C# using recursion

This is just a quick C# console program that traverses through directories and subdirectories given a directory path using recursion. Specifically, it’s a function that takes a directory path as a parameter, recursively traverses through all its directories and subdirectories, and outputs a JSON string representing the tree structure along with the files in each directory. I also discuss two versions – first version uses serialization, and one doesn’t.

Contents

Build a JSON tree of a directory using serialization

This example traverses a directory and its subdirectories, and builds a JSON tree by serializing a directory object into string before returning that string.

This example uses the Newtonsoft.Json library for JSON serialization. You can install it via NuGet Package Manager:

Install-Package Newtonsoft.Json

And here is the full source code.

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        string directoryPath = "C:\\Your\\Directory\\Path";
        string jsonResult = GenerateDirectoryTreeJson(directoryPath);
        Console.WriteLine(jsonResult);
    }

    static string GenerateDirectoryTreeJson(string directoryPath)
    {
        DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
        return JsonConvert.SerializeObject(GenerateDirectoryTree(directoryInfo), Formatting.Indented);
    }

    static DirectoryNode GenerateDirectoryTree(DirectoryInfo directoryInfo)
    {
        DirectoryNode node = new DirectoryNode
        {
            Name = directoryInfo.Name,
            Files = directoryInfo.GetFiles().Length > 0 ? directoryInfo.GetFiles().Select(file => file.Name).ToArray() : null,
            Subdirectories = new List<DirectoryNode>()
        };

        foreach (var subdirectoryInfo in directoryInfo.GetDirectories())
        {
            node.Subdirectories.Add(GenerateDirectoryTree(subdirectoryInfo));
        }

        return node;
    }
}

class DirectoryNode
{
    public string Name { get; set; }
    public string[] Files { get; set; }
    public List<DirectoryNode> Subdirectories { get; set; }
}

This code does the following:

GenerateDirectoryTreeJson starts the process by passing the root directory path and serializes the result into a JSON string.
GenerateDirectoryTree recursively generates the tree structure by creating DirectoryNode objects for each directory.
DirectoryNode class contains properties for the directory name, an array of file names within that directory, and a list of subdirectories represented by DirectoryNode.

This will output a JSON string representing the directory structure and files within each directory in a hierarchical manner. Adjust the paths and customize it further based on your specific requirements.

Build a JSON tree of a directory path by concatenating string together.

This version builds a JSON string manually by concatenating strings together. It constructs the JSON object for each directory node without using any external libraries for serialization. Below is the source code.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string directoryPath = "C:\\Your\\Directory\\Path";
        string jsonResult = GenerateDirectoryTreeJson(directoryPath);
        Console.WriteLine(jsonResult);
    }

    static string GenerateDirectoryTreeJson(string directoryPath)
    {
        DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
        return GenerateDirectoryTree(directoryInfo);
    }

    static string GenerateDirectoryTree(DirectoryInfo directoryInfo)
    {
        string json = "{";
        json += $"\"Name\": \"{directoryInfo.Name}\",";
        json += "\"Subdirectories\": [";

        DirectoryInfo[] subdirectories = directoryInfo.GetDirectories();
        for (int i = 0; i < subdirectories.Length; i++)
        {
            if (i > 0)
            {
                json += ",";
            }
            json += GenerateDirectoryTree(subdirectories[i]);
        }

        json += "]}";

        return json;
    }
}

Conclusion

In this blog post, I talked about how to implement a recursive function that traverses a directory and its subdirectories and that outputs a JSON string representing the tree structure along with the files in each directory. I showed a version of the program that uses Newtonsoft.Json library for JSON serialization. I also showed a second version that doesn’t use serialization, but instead concatenates strings together.

Alejandrio Vasay
Alejandrio Vasay

Welcome to Coder Schmoder! I'm a .NET developer with a 15+ years of web and software development experience. I created this blog to impart my knowledge of programming to those who are interested in learning are just beginning in their programming journey.

I live in DFW, Texas and currently working as a .NET /Web Developer. I earned my Master of Computer Science degree from Texas A&M University, College Station, Texas. I hope, someday, to make enough money to travel to my birth country, the Philippines, and teach software development to people who don't have the means to learn it.

Articles: 22

Leave a Reply

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