When dealing with large directory structures, printing results to the console is not enough. Exporting the file tree to a CSV file allows you to analyze it in Excel, Power BI, or any reporting tool.
Exporting Directory and File Listings to CSV in C#
When dealing with large directory structures, printing results to the console is not enough. Exporting the file tree to a CSV file allows you to analyze it in Excel, Power BI, or any reporting tool.
Step 1: Define the CSV Structure
A simple CSV format might include the following columns:
- Type → Directory or File
- Path → Full path of the item
- Name → Only the file/folder name
Step 2: Recursive Function That Writes to CSV
We’ll extend the recursive function from Version 3 to save entries into a List<string> that will later be written to a .csv file.
using System;
using System.IO;
using System.Collections.Generic;
class Program
{
static void Main()
{
string folderPath = @"C:\Test";
string csvPath = @"C:\output.csv";
var rows = new List<string>();
rows.Add("Type,Path,Name"); // CSV header
try
{
if (Directory.Exists(folderPath))
{
Console.WriteLine($"📂 Exporting recursive listing for: {folderPath}");
ListDirectory(folderPath, rows);
File.WriteAllLines(csvPath, rows);
Console.WriteLine($"✅ Export completed. CSV saved at: {csvPath}");
}
else
{
Console.WriteLine("The specified folder does not exist.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void ListDirectory(string path, List<string> rows)
{
try
{
// Add current directory
rows.Add($"Directory,\"{path}\",\"{Path.GetFileName(path)}\"");
// Add files
foreach (var file in Directory.GetFiles(path))
{
rows.Add($"File,\"{file}\",\"{Path.GetFileName(file)}\"");
}
// Recurse into subdirectories
foreach (var dir in Directory.GetDirectories(path))
{
ListDirectory(dir, rows);
}
}
catch (UnauthorizedAccessException)
{
rows.Add($"Directory,\"{path}\",ACCESS DENIED");
}
}
}
Step 3: Example Output in CSV
If the folder contains:
C:\Test
┣ Project1
┃ ┗ data.csv
┣ Logs
┃ ┗ log1.txt
┗ readme.txt
The output.csv will look like:
Type,Path,Name
Directory,"C:\Test","Test"
File,"C:\Test\readme.txt","readme.txt"
Directory,"C:\Test\Project1","Project1"
File,"C:\Test\Project1\data.csv","data.csv"
Directory,"C:\Test\Logs","Logs"
File,"C:\Test\Logs\log1.txt","log1.txt"
Technical Summary
| Step | Technique | Method |
|---|---|---|
| 1 | Store results in memory | List<string> |
| 2 | Add CSV header | "Type,Path,Name" |
| 3 | Write directories | rows.Add("Directory,...") |
| 4 | Write files | rows.Add("File,...") |
| 5 | Export to file | File.WriteAllLines(csvPath, rows) |
✅ This approach gives you a clean CSV file of all directories and files, which can be directly opened in Excel or imported into data analysis tools.
