Reading and writing files
Course contents (16 lessons)
- Getting started
- Installing the .NET 10 SDK and checking it works
- Your first console app and top-level statements
- The building blocks
- Variables and basic types
- Working with strings and interpolation
- Reading input and writing output
- Making decisions and repeating work
- Conditionals and switch expressions
- Loops: for, while, do and foreach
- Collections and methods
- Arrays and List of T
- Writing your own methods
- Objects and classes
- Classes and objects
- Properties, encapsulation and object initialisers
- Handling null safely
- Errors and files
- Exceptions: try, catch, finally and throw
- Reading and writing files
- Final project: expense tracker
- Expense tracker, part 1: planning, model and storage
- Expense tracker, part 2: the menu and summaries
Making data last
Everything in memory disappears when the program ends. To keep data you write it to a file. The File class in the System.IO namespace has simple methods for this. They are included in the implicit usings, so you can call them straight away.
The quick methods
For small files, one line does the job.
File.WriteAllText(path, text)creates or overwrites a file.File.AppendAllText(path, text)adds to the end.File.ReadAllText(path)returns the whole file as one string.File.ReadAllLines(path)returns a string array, one item per line.File.Exists(path)tells you whether it is there.
using System.Text.Json;
string folder = Path.Combine(AppContext.BaseDirectory, "data");
Directory.CreateDirectory(folder);
// 1. Plain text
string notesPath = Path.Combine(folder, "notes.txt");
File.WriteAllText(notesPath, "First line" + Environment.NewLine);
File.AppendAllText(notesPath, "Second line" + Environment.NewLine);
foreach (string line in File.ReadAllLines(notesPath))
{
Console.WriteLine($"> {line}");
}
// 2. Writing with a StreamWriter and a using statement
string logPath = Path.Combine(folder, "log.txt");
using (var writer = new StreamWriter(logPath, append: true))
{
writer.WriteLine($"{DateTime.Now:s} program started");
}
// 3. Saving a list of objects as JSON
var books = new List<Book>
{
new Book("Clean Code", "Robert C. Martin", 2008),
new Book("The Pragmatic Programmer", "Andrew Hunt and David Thomas", 1999)
};
string jsonPath = Path.Combine(folder, "books.json");
var options = new JsonSerializerOptions { WriteIndented = true };
File.WriteAllText(jsonPath, JsonSerializer.Serialize(books, options));
// 4. Reading it back
List<Book> loaded = new();
if (File.Exists(jsonPath))
{
string json = File.ReadAllText(jsonPath);
loaded = JsonSerializer.Deserialize<List<Book>>(json) ?? new List<Book>();
}
foreach (Book b in loaded)
{
Console.WriteLine($"{b.Title} by {b.Author} ({b.Year})");
}
Console.WriteLine($"Files are in: {folder}");
record Book(string Title, string Author, int Year);
Walking through it
We start by building a path with Path.Combine. Never join paths by hand with + and slashes. Windows uses backslashes and Linux uses forward slashes. Path.Combine picks the right one. AppContext.BaseDirectory is the folder where the program runs, so the example works on any machine without hard-coded drive letters. Directory.CreateDirectory does nothing if the folder already exists, so you can call it safely every time.
The text section writes a line, appends another and reads both back. Environment.NewLine is the correct line ending for the current system.
The StreamWriter example introduces using. A writer holds the file open. The using block closes it at the closing brace, even if an exception occurs. That is the cleanup job from the exceptions lesson, done for you. Forgetting it can leave the last lines unwritten or the file locked. Use StreamWriter when you write many lines over time, such as a log.
The JSON section is how most small programs save data. JsonSerializer.Serialize turns a list of objects into text, and Deserialize turns it back. The record Book(...) line declares a small data class in one line. We cover records in the advanced course. For now, treat it as a class with three properties. The ?? new List<Book>() at the end handles the case where the file holds the word null.
What can go wrong
File operations fail more often than most code: the file may not exist, another program may have it open, or you may not have permission. Catch IOException and UnauthorizedAccessException where you can show the user a useful message. Check File.Exists before you read a file that may not be there yet, for example on the first run.
Corrupted JSON throws a JsonException. For data you care about, catch it and tell the user instead of crashing.
Common mistakes
- Using relative paths and not knowing where they point. A relative path starts from the current working directory, which depends on how the program is launched. Build the path from a known folder.
- Using WriteAllText when you meant to append. It replaces the whole file.
- Not disposing writers. Always use
using. - Hard-coding backslashes. Use
Path.Combine.
Try it yourself
- Write a program that asks for a line of text and appends it, with the time, to a journal file. Each run should add a new entry.
- Add an option to print the whole journal.
- Save a list of your favourite films to JSON, then change the program to load it at start-up and add one more each run.
using System.Text.Json;
string folder = Path.Combine(AppContext.BaseDirectory, "data");
Directory.CreateDirectory(folder);
// 1. Plain text
string notesPath = Path.Combine(folder, "notes.txt");
File.WriteAllText(notesPath, "First line" + Environment.NewLine);
File.AppendAllText(notesPath, "Second line" + Environment.NewLine);
foreach (string line in File.ReadAllLines(notesPath))
{
Console.WriteLine($"> {line}");
}
// 2. Writing with a StreamWriter and a using statement
string logPath = Path.Combine(folder, "log.txt");
using (var writer = new StreamWriter(logPath, append: true))
{
writer.WriteLine($"{DateTime.Now:s} program started");
}
// 3. Saving a list of objects as JSON
var books = new List<Book>
{
new Book("Clean Code", "Robert C. Martin", 2008),
new Book("The Pragmatic Programmer", "Andrew Hunt and David Thomas", 1999)
};
string jsonPath = Path.Combine(folder, "books.json");
var options = new JsonSerializerOptions { WriteIndented = true };
File.WriteAllText(jsonPath, JsonSerializer.Serialize(books, options));
// 4. Reading it back
List<Book> loaded = new();
if (File.Exists(jsonPath))
{
string json = File.ReadAllText(jsonPath);
loaded = JsonSerializer.Deserialize<List<Book>>(json) ?? new List<Book>();
}
foreach (Book b in loaded)
{
Console.WriteLine($"{b.Title} by {b.Author} ({b.Year})");
}
Console.WriteLine($"Files are in: {folder}");
record Book(string Title, string Author, int Year);
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account