Learn C# in Y Minutes
C# 14 · .NET 10

13. Files & Directories

The System.IO namespace lets you read and write files, create folders, and build paths that work on every operating system. It is already imported for you, so File, Directory, and Path are ready to use.

The examples work inside the system temp folder and clean up after themselves, so running them leaves nothing behind.

File: quick one-liners

The static File class does a whole job in one call: open the file, read or write, close it again.

  • WriteAllText creates the file, or overwrites it if it exists.
  • AppendAllText adds to the end instead.
  • ReadAllText returns one string; ReadAllLines returns an array of lines.
app/13-files/FileBasics.cs
var dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "lesson13-basics")).FullName;
var notes = Path.Combine(dir, "notes.txt");

File.WriteAllText(notes, "Buy milk\n");
Console.WriteLine($"Exists? {File.Exists(notes)}");

File.AppendAllText(notes, "Learn C#\n");
Console.Write(File.ReadAllText(notes));

string[] lines = File.ReadAllLines(notes);
Console.WriteLine($"Lines: {lines.Length}, first: {lines[0]}");

var backup = Path.Combine(dir, "notes.bak");
File.Copy(notes, backup, overwrite: true);
Console.WriteLine($"Backup exists? {File.Exists(backup)}");

File.Delete(notes);
Console.WriteLine($"Notes exists after delete? {File.Exists(notes)}");

Directory.Delete(dir, recursive: true);
Exists? True
Buy milk
Learn C#
Lines: 2, first: Buy milk
Backup exists? True
Notes exists after delete? False

FileInfo: one file, many operations

FileInfo is an object that represents one file. It exposes properties like Name, Extension, and Length (size in bytes).

Rule of thumb: use File for a single operation. Use FileInfo when you do several things with the same file, because File re-checks permissions on every call.

app/13-files/FileInfoDemo.cs
var dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "lesson13-info")).FullName;
File.WriteAllText(Path.Combine(dir, "report.csv"), "id,total\n1,250\n");

var file = new FileInfo(Path.Combine(dir, "report.csv"));

Console.WriteLine($"Name: {file.Name}");
Console.WriteLine($"Extension: {file.Extension}");
Console.WriteLine($"Size: {file.Length} bytes");
Console.WriteLine($"Exists? {file.Exists}");

var copy = file.CopyTo(Path.Combine(dir, "report-copy.csv"));
Console.WriteLine($"Copied to: {copy.Name}");

copy.Delete();
Directory.Delete(dir, recursive: true);
Name: report.csv
Extension: .csv
Size: 15 bytes
Exists? True
Copied to: report-copy.csv

Directory and DirectoryInfo

The same pair exists for folders. CreateDirectory creates every missing folder in the path and does nothing if it already exists. GetFiles accepts a search pattern like "*.txt".

app/13-files/Directories.cs
var root = Path.Combine(Path.GetTempPath(), "lesson13-dirs");
Directory.CreateDirectory(Path.Combine(root, "images"));
Directory.CreateDirectory(Path.Combine(root, "docs"));
File.WriteAllText(Path.Combine(root, "docs", "a.txt"), "A");
File.WriteAllText(Path.Combine(root, "docs", "b.txt"), "B");
File.WriteAllText(Path.Combine(root, "docs", "c.md"), "C");

string[] textFiles = Directory.GetFiles(Path.Combine(root, "docs"), "*.txt");
Array.Sort(textFiles);
foreach (var f in textFiles)
    Console.WriteLine($"Text file: {Path.GetFileName(f)}");

string[] folders = Directory.GetDirectories(root);
Console.WriteLine($"Folders: {folders.Length}");

var info = new DirectoryInfo(Path.Combine(root, "docs"));
Console.WriteLine($"{info.Name} has {info.GetFiles().Length} files");

Directory.Delete(root, recursive: true);
Console.WriteLine($"Root exists? {Directory.Exists(root)}");
Text file: a.txt
Text file: b.txt
Folders: 2
docs has 3 files
Root exists? False

GetFiles does not promise any order. Sort the result when order matters.

Path

Never build paths by gluing strings with "/" or "\\". Path.Combine uses the right separator for the operating system: you will see backslashes on Windows. The other Path methods only work on the text; they never touch the disk.

app/13-files/Paths.cs
string path = Path.Combine("data", "reports", "sales-2026.csv");

Console.WriteLine(path);
Console.WriteLine($"File name: {Path.GetFileName(path)}");
Console.WriteLine($"Without extension: {Path.GetFileNameWithoutExtension(path)}");
Console.WriteLine($"Extension: {Path.GetExtension(path)}");
Console.WriteLine($"Folder: {Path.GetDirectoryName(path)}");
Console.WriteLine($"Changed: {Path.ChangeExtension(path, ".json")}");
data/reports/sales-2026.csv
File name: sales-2026.csv
Without extension: sales-2026
Extension: .csv
Folder: data/reports
Changed: data/reports/sales-2026.json

Async versions

Disk access is slow compared to the CPU. Every method above has an Async twin that lets the program do other work while it waits. Put await in front of the call. You will learn how this works in the intermediate course; for now, recognize the pattern.

app/13-files/AsyncFiles.cs
var dir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "lesson13-async")).FullName;
var file = Path.Combine(dir, "log.txt");

await File.WriteAllTextAsync(file, "Server started\n");
await File.AppendAllLinesAsync(file, ["Request 1", "Request 2"]);

string content = await File.ReadAllTextAsync(file);
Console.Write(content);

Directory.Delete(dir, recursive: true);
Server started
Request 1
Request 2

Web servers handle many requests at once, so always use the Async file methods there. A typical use is serving or saving uploaded files; build their paths from IWebHostEnvironment.ContentRootPath, never from user input directly.

Program.cs
app.MapGet("/terms", async (IWebHostEnvironment env) =>
{
    var path = Path.Combine(env.ContentRootPath, "content", "terms.txt");
    return Results.Text(await File.ReadAllTextAsync(path));
});

Quick quiz