view folder file tree in csharp

To view the folder file tree in C#, we can use the Directory class from the System.IO namespace. Here's an example code snippet that uses recursion to display the file tree of a given directory:

main.cs
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string startFolder = @"C:\ExampleDirectory";

        if (Directory.Exists(startFolder))
        {
            DisplayDirectoryTree(startFolder);
        }
        else
        {
            Console.WriteLine("The specified directory does not exist.");
        }

        Console.ReadLine();
    }

    static void DisplayDirectoryTree(string folder)
    {
        Console.WriteLine(folder);

        try
        {
            foreach (string file in Directory.GetFiles(folder))
            {
                Console.WriteLine(file);
            }

            foreach (string subDir in Directory.GetDirectories(folder))
            {
                DisplayDirectoryTree(subDir);
            }
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("Access to this directory is denied.");
        }
    }
}
945 chars
44 lines

In this code, we first check if the specified starting directory exists. If it does, we call the DisplayDirectoryTree method and pass in the starting directory as an argument.

The DisplayDirectoryTree method displays the name of the current directory using the Console.WriteLine method. It then uses the GetFiles and GetDirectories methods from the Directory class to obtain the names of all files and directories within the current directory.

If there are any files in the current directory, their names are displayed using the Console.WriteLine method. If there are any subdirectories, the DisplayDirectoryTree method is called recursively with these subdirectories as arguments.

The code also catches any UnauthorizedAccessExceptions that may occur if we don't have permission to access a certain directory. Overall, this code should be able to display the file tree of most directories on a Windows machine.

gistlibby LogSnag