view folder file subfolders tree in csharp

To view the folder, file, and subfolder tree in C#, you can use the Directory class and DirectoryInfo class. Here's a sample code that recursively prints the tree structure of a given directory:

main.cs
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // the root directory to print
        string rootDir = @"C:\Users\Public";

        // call the recursive method to print the tree structure
        PrintDirectoryTree(rootDir, "");
    }

    static void PrintDirectoryTree(string rootDir, string indent)
    {
        Console.WriteLine(indent + rootDir);

        try
        {
            // get all the sub-directories of the root directory
            string[] subDirs = Directory.GetDirectories(rootDir);

            // recursively print the tree structure of each sub-directory
            foreach (string subDir in subDirs)
            {
                PrintDirectoryTree(subDir, indent + "    ");
            }

            // get all the files in the root directory
            string[] files = Directory.GetFiles(rootDir);

            // print the name of each file in the root directory
            foreach (string file in files)
            {
                Console.WriteLine(indent + "    " + Path.GetFileName(file));
            }
        }
        catch
        {
            // ignore exceptions such as access denied
        }
    }
}
1205 chars
45 lines

The Directory.GetDirectories method returns an array of strings representing the sub-directories of the given directory. The Directory.GetFiles method returns an array of strings representing the files in the given directory. The Path.GetFileName method returns the name of a file given its full path.

The PrintDirectoryTree method is called recursively to print the tree structure of each sub-directory. The indent parameter is used to add spaces to the output to indicate the level of indentation of each directory and file. The try block is used to ignore exceptions such as access denied.

gistlibby LogSnag