Sometimes you need more than just listing files and folders from a single directory. You may want to scan all subdirectories recursively and show the complete structure. In .NET, this can be done easily with the System.IO namespace.
Recursive Directory and File Listing in C#
Sometimes you need more than just listing files and folders from a single directory. You may want to scan all subdirectories recursively and show the complete structure. In .NET, this can be done easily with the System.IO namespace.
Why Recursive Listing?
- Shallow listing (only top-level) is useful for quick scans.
- Recursive listing is needed for deeper analysis, such as backups, file explorers, or migration scripts.
Step 1: Use the Recursive Search Options
The Directory class provides overloads that support recursion:
Directory.GetFiles(path, "*", SearchOption.AllDirectories)Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
Alternatively, you can write your own recursive function to have full control over formatting and error handling.
Step 2: Recursive Function Example
Here is a custom recursive method that prints both directories and files:
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = @"C:\Test";
try
{
if (Directory.Exists(folderPath))
{
Console.WriteLine($"📂 Recursive listing for: {folderPath}\n");
ListDirectory(folderPath, 0);
}
else
{
Console.WriteLine("The specified folder does not exist.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void ListDirectory(string path, int indent)
{
try
{
// Print current directory
Console.WriteLine($"{new string(' ', indent)}[DIR] {Path.GetFileName(path)}");
// List all files in current directory
foreach (var file in Directory.GetFiles(path))
{
Console.WriteLine($"{new string(' ', indent + 2)}- {Path.GetFileName(file)}");
}
// Recursively list subdirectories
foreach (var dir in Directory.GetDirectories(path))
{
ListDirectory(dir, indent + 2);
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine($"{new string(' ', indent)}[ACCESS DENIED]");
}
}
}
Step 3: Example Output
If the folder C:\Test contains:
C:\Test
┣ Project1
┃ ┣ data.csv
┃ ┗ notes.txt
┣ Logs
┃ ┗ log1.txt
┗ readme.txt
The program will print:
📂 Recursive listing for: C:\Test
[DIR] Test
- readme.txt
[DIR] Project1
- data.csv
- notes.txt
[DIR] Logs
- log1.txt
Technical Summary
| Step | Technique | Method |
|---|---|---|
| 1 | Print directories | Path.GetFileName(path) |
| 2 | List files | Directory.GetFiles(path) |
| 3 | Recurse into subdirectories | ListDirectory(dir, indent + 2) |
| 4 | Handle access issues | try/catch UnauthorizedAccessException |
✅ With this recursive approach, you can build utilities similar to the tree command, generate reports of file structures, or prepare data for migrations.
