๐Ÿ  VisualStudioTutor.com  ยท  C# Tutorial Home  ยท  C# Lesson 13 of 40
Lesson 13 of 40 Core C# Intermediate โฑ 30 min

File I/O & Streams

Read and write files with File, FileStream, StreamReader/Writer, async file I/O, and Path/Directory utilities.

Part 1: Reading and Writing Text Files

// Write all text
await File.WriteAllTextAsync("output.txt", "Hello, file!");

// Append lines
await File.AppendAllLinesAsync("log.txt", ["line1","line2"]);

// Read all lines
string[] lines = await File.ReadAllLinesAsync("data.csv");

Part 2: StreamReader & StreamWriter

await using var writer = new StreamWriter("big.txt");
await writer.WriteLineAsync("Streaming large files efficiently");

await using var reader = new StreamReader("big.txt");
while (!reader.EndOfStream)
{
    var line = await reader.ReadLineAsync();
    Process(line);
}

Part 3: Path & Directory Utilities

Path.Combine("C:\Users","Alice","docs"); // OS-safe
Path.GetExtension("report.pdf"); // ".pdf"
Path.GetFileNameWithoutExtension("report.pdf"); // "report"
Directory.CreateDirectory("output/reports");
var files = Directory.GetFiles(".","*.cs", SearchOption.AllDirectories);

Part 4: JSON Serialization with Files

var data = new AppSettings { Theme = "dark" };
var json = JsonSerializer.Serialize(data);
await File.WriteAllTextAsync("settings.json", json);

var loaded = JsonSerializer.Deserialize<AppSettings>(await File.ReadAllTextAsync("settings.json"));

C# in Visual Studio 2026

๐Ÿ“˜ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition