Skip to content

Instantly share code, notes, and snippets.

@imhalawa
Created April 15, 2026 18:47
Show Gist options
  • Select an option

  • Save imhalawa/8e06b605b62f7d82e1bc17d55f30a21b to your computer and use it in GitHub Desktop.

Select an option

Save imhalawa/8e06b605b62f7d82e1bc17d55f30a21b to your computer and use it in GitHub Desktop.
Recursive DFS in C# that prints a directory tree to the console with tree-style connectors, threading the prefix string down each branch.
var path = @"";
if (!Directory.Exists(path))
{
throw new ArgumentException("Invalid directory path");
}
PrintFileSystemEntries(path);
return;
void PrintFileSystemEntries(string path)
{
DFS(new DirectoryWithMeta(path, 0));
}
void DFS(DirectoryWithMeta directory, string prefix = "", bool isLast = true)
{
var entries = Directory.EnumerateFileSystemEntries(directory.Path).ToList();
var connector = directory.Level == 0 ? "" : (isLast ? "└── " : "├── ");
Console.WriteLine($"{prefix}{connector}{directory.Path.Split(Path.DirectorySeparatorChar).Last()}");
var childPrefix = directory.Level == 0 ? "" : prefix + (isLast ? " " : "│ ");
for (int i = 0; i < entries.Count; i++)
{
var entry = entries[i];
bool entryIsLast = i == entries.Count - 1;
var entryConnector = entryIsLast ? "└── " : "├── ";
if (File.Exists(entry))
{
Console.WriteLine($"{childPrefix}{entryConnector}{entry.Split(Path.DirectorySeparatorChar).Last()}");
}
else
{
DFS(new DirectoryWithMeta(entry, directory.Level + 1), childPrefix, entryIsLast);
}
}
}
record DirectoryWithMeta(string Path, int Level);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment