A program that forgets everything when it closes is not much use: a to-do list, game progress and settings must survive a restart. The simplest place to keep data is a file. In the lesson «async/await and a small console project» you already read lines with File.ReadAllLinesAsync; now let's look at the whole toolbox: paths and folders, text and encodings, streams, and the most popular data format of today — JSON.
Paths, folders and files
Windows separates the parts of a path with \, Linux and macOS with /, so never glue paths together with + "\\" +. The Path class picks the separator itself and works only with strings — it never touches the disk. The real work on the disk is done by Directory (folders) and File (files).
string folder = Path.Combine("data", "2026");
Directory.CreateDirectory(folder);
string file = Path.Combine(folder, "scores.txt");
Console.WriteLine(file);
Console.WriteLine(Path.GetFileName(file));
Console.WriteLine(Path.GetFileNameWithoutExtension(file));
Console.WriteLine(Path.GetExtension(file));
Console.WriteLine(Path.ChangeExtension(file, ".json"));
File.WriteAllText(file, "Aysel;95");
File.WriteAllText(Path.Combine(folder, "notes.md"), "todo");
Console.WriteLine(File.Exists(file));
foreach (string f in Directory.GetFiles(folder, "*.txt"))
Console.WriteLine($"Found: {Path.GetFileName(f)}");
Directory.Delete("data", recursive: true);
Console.WriteLine(Directory.Exists("data"));Expected output
data\2026\scores.txt scores.txt scores .txt data\2026\scores.json True Found: scores.txt False
/Directory.CreateDirectory creates all the missing levels at once and does nothing if the folder already exists. Directory.GetFiles(folder, "*.txt") returns the files that match the mask — notes.md did not make the list. Directory.Delete("data", recursive: true) deletes the folder together with its contents, so be careful. Note: a relative path like data is resolved against the current working directory — wherever you started the program from — not against the program file. The program's own folder is in AppContext.BaseDirectory.
| Method | What it does |
|---|---|
File.ReadAllText / File.WriteAllText | reads / writes the whole file as one string (old content is replaced) |
File.ReadAllLines / File.WriteAllLines | reads / writes an array of lines |
File.AppendAllText / File.AppendAllLines | adds to the end of the file and creates it if it does not exist |
File.ReadLines | reads lines one by one, on demand — for big files |
File.Exists / File.Copy / File.Move / File.Delete | check, copy, move, delete |
Text, encodings and UTF-8
EncodingDefinition
The rule that turns characters into bytes and back. A file stores only bytes; for text to be read correctly, the writer and the reader must use the same encoding.
By default .NET writes and reads files in UTF-8 without a BOM. In UTF-8 Latin letters take 1 byte, while letters such as ə, ş and ğ take 2 bytes. The example below measures this and shows what happens when you write with an old encoding that does not know the Azerbaijani letters.
using System.Text;
Console.OutputEncoding = Encoding.UTF8;
File.WriteAllText("city.txt", "Gəncə");
Console.WriteLine("Gəncə".Length);
Console.WriteLine(new FileInfo("city.txt").Length);
Console.WriteLine(File.ReadAllText("city.txt"));
File.WriteAllLines("cities.txt", ["Bakı", "Gəncə", "Şəki"]);
File.AppendAllLines("cities.txt", ["Ağdam"]);
string[] lines = File.ReadAllLines("cities.txt");
Console.WriteLine($"{lines.Length} lines, last: {lines[^1]}");
foreach (string line in File.ReadLines("cities.txt").Where(l => l.Contains('ə')))
Console.WriteLine(line);
File.WriteAllText("legacy.txt", "Gəncə", Encoding.Latin1);
Console.WriteLine(File.ReadAllText("legacy.txt"));Expected output
5 7 Gəncə 4 lines, last: Ağdam Gəncə Şəki G?nc?
Latin1 cannot store the letter əGəncə contains two ə letters, and each takes 2 bytes, so 5 characters become 7 bytes on disk. File.ReadLines reads lines on demand, so you can filter them with LINQ straight away without loading the whole file into memory. The last line is a warning: Latin1 has no ə, so it was replaced with ? — the information is lost for good. The first line, Console.OutputEncoding = Encoding.UTF8, makes the Windows console show these letters correctly.
Streams: StreamReader, StreamWriter and using
ReadAllText loads the whole file into memory. That is no good for a gigabyte log file: such files must be read and written as a stream, piece by piece. A StreamWriter first collects text in a buffer in memory and writes it to disk in chunks, which is fast. But the buffer is fully flushed, and the file closed, only when Dispose (or Flush) is called. using guarantees that — even if an exception happens inside the block.
using (var writer = new StreamWriter("log.txt"))
{
writer.WriteLine("08:00 Lesson started");
writer.WriteLine("08:45 Break");
writer.Write("09:00 ");
writer.WriteLine("Lesson 2");
}
using var reader = new StreamReader("log.txt");
int number = 0;
string? line;
while ((line = reader.ReadLine()) is not null)
{
number++;
Console.WriteLine($"{number}: {line}");
}
var forgotten = new StreamWriter("lost.txt");
forgotten.Write("Important data");
Console.WriteLine(new FileInfo("lost.txt").Length);
forgotten.Dispose();
Console.WriteLine(new FileInfo("lost.txt").Length);Expected output
1: 08:00 Lesson started 2: 08:45 Break 3: 09:00 Lesson 2 0 14
using closes the file, while a forgotten StreamWriter keeps the data in its bufferwhile ((line = reader.ReadLine()) is not null) is the classic reading loop: ReadLine returns null at the end of the file. using var reader is closed at the end of the enclosing scope — here, the end of the program — rather than at the end of a block. The last four lines show the mistake: 14 characters were written to forgotten, yet the file is still empty (0 bytes) because the text sits in the buffer. Only after Dispose does the file have 14 bytes. Had Dispose never been called, the data could have been lost even when the program ended.
A file operation can always fail: the file was deleted, the folder does not exist, permission is missing, or another program has the file open. Checking with File.Exists is not enough — the file can disappear between the check and the read. So catch the exceptions, the specific ones first:
string[] paths = ["missing.txt", Path.Combine("no-such-folder", "a.txt")];
foreach (string p in paths)
{
try
{
Console.WriteLine(File.ReadAllText(p));
}
catch (FileNotFoundException)
{
Console.WriteLine($"No such file: {Path.GetFileName(p)}");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine($"No such folder for: {Path.GetFileName(p)}");
}
catch (IOException ex)
{
Console.WriteLine($"Other I/O error: {ex.Message}");
}
}
Console.WriteLine(typeof(FileNotFoundException).BaseType?.Name);Expected output
No such file: missing.txt No such folder for: a.txt IOException
FileNotFoundException and DirectoryNotFoundException derive from IOExceptionThe general IOException goes last: in the reverse order the compiler reports error CS0160, because the specific catch could never be reached. UnauthorizedAccessException, thrown when permission is missing, is not a child of IOException — catch it separately if you need to. The async versions follow the same rules but do not block the thread while waiting, which matters for graphical apps and servers:
await File.WriteAllLinesAsync("scores.txt", ["Aysel;95", "Murad;78", "bad line", "Leyla;88"]);
int count = 0, total = 0;
await foreach (string line in File.ReadLinesAsync("scores.txt"))
{
string[] parts = line.Split(';');
if (parts.Length != 2 || !int.TryParse(parts[1], out int score)) continue;
count++;
total += score;
}
await using (var writer = new StreamWriter("report.txt"))
{
await writer.WriteLineAsync($"Students: {count}");
await writer.WriteLineAsync($"Average: {total / count}");
}
Console.Write(await File.ReadAllTextAsync("report.txt"));Expected output
Students: 3 Average: 87
File.ReadLinesAsync yields lines to await foreach, and await using closes the file asynchronouslyFile.ReadLinesAsync returns an asynchronous stream (IAsyncEnumerable<string>), which you know from the lesson «Asynchronous and parallel programming». The bad line (bad line) was skipped, and the other three scores were added up: (95 + 78 + 88) / 3 = 87 (integer division).
JSON with System.Text.Json
JSON is a simple format for writing objects as text: "name": value pairs inside {}, lists inside [], strings, numbers, true, false and null. Web APIs, configuration files and mobile apps all speak this format. .NET has a built-in library for it, System.Text.Json, so no package is needed.
SerialisationDefinition
Turning an object into text (for example JSON) so that it can be stored or sent. The reverse process, rebuilding the object from text, is called deserialisation.
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;
Console.OutputEncoding = Encoding.UTF8;
var student = new Student("Aysel Məmmədova", 17, ["Math", "Physics"], null);
Console.WriteLine(JsonSerializer.Serialize(student));
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
Console.WriteLine(JsonSerializer.Serialize(student, options));
record Student(string FullName, int Age, List<string> Subjects, string? Email);Expected output
{"FullName":"Aysel M\u0259mm\u0259dova","Age":17,"Subjects":["Math","Physics"],"Email":null}
{
"fullName": "Aysel Məmmədova",
"age": 17,
"subjects": [
"Math",
"Physics"
]
}The first line is the default result: names as in C# (FullName), everything on one line, null written out, and the letter ə encoded as \u0259. This is valid JSON and reads back correctly, but it is unreadable for people. The options fix that: WriteIndented adds line breaks and indentation, JsonNamingPolicy.CamelCase starts names with a lowercase letter as is usual on the web, JavaScriptEncoder.Create(UnicodeRanges.All) keeps the letters as they are, and JsonIgnoreCondition.WhenWritingNull leaves out empty fields.
using System.Text;
using System.Text.Json;
Console.OutputEncoding = Encoding.UTF8;
string json = """
[
{ "fullName": "Murad Əliyev", "age": 16, "subjects": ["History"] },
{ "FULLNAME": "Leyla Quliyeva", "age": 17, "subjects": [], "email": "leyla@example.com" }
]
""";
List<Student>? students = JsonSerializer.Deserialize<List<Student>>(json, JsonSerializerOptions.Web);
foreach (Student s in students ?? [])
Console.WriteLine($"{s.FullName}, {s.Age}, subjects: {s.Subjects.Count}, email: {s.Email ?? "none"}");
try
{
JsonSerializer.Deserialize<Student>("""{ "fullName": "Elvin", "age": "seventeen" }""", JsonSerializerOptions.Web);
}
catch (JsonException ex)
{
Console.WriteLine($"Bad JSON: {ex.Message}");
}
record Student(string FullName, int Age, List<string> Subjects, string? Email);Expected output
Murad Əliyev, 16, subjects: 1, email: none Leyla Quliyeva, 17, subjects: 0, email: leyla@example.com Bad JSON: The JSON value could not be converted to Student. Path: $.age | LineNumber: 0 | BytePositionInLine: 41.
null, a wrong type gives a JsonExceptionRecords are created through their constructor: the serializer matches the JSON names with the constructor parameters. With the Web options even "FULLNAME" was recognised, and email, missing for the first student, became null. "age": "seventeen" cannot become a number, so a JsonException was thrown, and its message shows where the problem is: $.age. If a JSON name differs from the C# name, put [JsonPropertyName("full_name")] on the property; mark a property that must never be serialised with [JsonIgnore].
Mini project: an expense tracker that saves to JSON
The model
record Expense(DateOnly Date, string Category, decimal Amount).DateOnlyis written to JSON as"2026-10-01", anddecimalis the exact type for money.Loading
LoadAsync: no file — an empty list; damaged JSON — a warning and an empty list; otherwiseDeserializeAsyncreads straight from the file stream.Safe saving
AddAsyncwrites the list to a temporary.tmpfile and then replaces the main file withFile.Move(..., overwrite: true). If the program crashes in the middle of writing, the old file stays intact.Trying it out
Add two expenses, read the file, then damage the file on purpose and make sure that loading does not crash.
class ExpenseStore(string path)
{
private static readonly JsonSerializerOptions Options =
new(JsonSerializerOptions.Web) { WriteIndented = true };
public async Task<List<Expense>> LoadAsync()
{
if (!File.Exists(path)) return [];
try
{
await using FileStream stream = File.OpenRead(path);
return await JsonSerializer.DeserializeAsync<List<Expense>>(stream, Options) ?? [];
}
catch (JsonException ex)
{
Console.WriteLine($"Warning: {Path.GetFileName(path)} is damaged ({ex.GetType().Name})");
return [];
}
}
public async Task AddAsync(Expense expense)
{
List<Expense> items = await LoadAsync();
items.Add(expense);
string temp = path + ".tmp";
await using (FileStream stream = File.Create(temp))
await JsonSerializer.SerializeAsync(stream, items, Options);
File.Move(temp, path, overwrite: true);
}
}ExpenseStore class (at the end of the file)using System.Text.Json;
File.Delete("expenses.json");
var store = new ExpenseStore("expenses.json");
Console.WriteLine($"Start: {(await store.LoadAsync()).Count} expenses");
await store.AddAsync(new Expense(new DateOnly(2026, 10, 1), "Books", 24));
await store.AddAsync(new Expense(new DateOnly(2026, 10, 2), "Metro", 1));
List<Expense> all = await store.LoadAsync();
Console.WriteLine($"Saved: {all.Count}, total {all.Sum(e => e.Amount)} AZN");
Console.WriteLine(await File.ReadAllTextAsync("expenses.json"));
await File.WriteAllTextAsync("expenses.json", "{ broken");
Console.WriteLine($"After damage: {(await store.LoadAsync()).Count} expenses");
record Expense(DateOnly Date, string Category, decimal Amount);Expected output
Start: 0 expenses
Saved: 2, total 25 AZN
[
{
"date": "2026-10-01",
"category": "Books",
"amount": 24
},
{
"date": "2026-10-02",
"category": "Metro",
"amount": 1
}
]
Warning: expenses.json is damaged (JsonException)
After damage: 0 expensesEvery AddAsync reads the file again and writes it out completely — for small data this is simple and reliable. DeserializeAsync and SerializeAsync work directly with the FileStream without building a string, so they save memory on big files. The damaged file did not stop the program: the user saw a warning. In a real app, rather than overwriting a damaged file, keep a copy of it (expenses.json.bak) so that the data can still be recovered by hand.
Summary and practice
Pathbuilds paths and takes them apart,DirectoryandFilework on the disk; relative paths are resolved against the current working directory.- .NET uses UTF-8 by default;
ə,şandğtake 2 bytes, and a wrong encoding destroys them for good. - Streams process big files piece by piece;
usingflushes the buffer and closes the file. JsonSerializer.Serialize/Deserializeturn an object into JSON and back;JsonSerializerOptionscontrols names, indentation and how letters are encoded.
Task 1: numbering lines
Problem
The file poem.txt has four lines: Roses are red, an empty line, Violets are blue, C# is fun. Use StreamReader and StreamWriter to create numbered.txt: skip the empty lines and put 1. , 2. … in front of the others. What will the result file contain?
Show solutionHide solution
Solution
using: using (var reader = new StreamReader("poem.txt")) and using (var writer = new StreamWriter("numbered.txt")).2) The loop:
while ((line = reader.ReadLine()) is not null).3) Skip an empty line with
if (line.Length == 0) continue; and write the others with writer.WriteLine($"{++number}. {line}");.4) When the block ends, both files are closed, and
numbered.txt contains:1. Roses are red2. Violets are blue3. C# is funTask 2: a settings file
Problem
You have record Settings(string Theme, int FontSize, bool Sound). Save new Settings("dark", 14, true) to settings.json with camelCase names and indentation, then read the file back, increase the font size by 2 and save it again. What is the final content of the file?
Show solutionHide solution
Solution
var options = new JsonSerializerOptions(JsonSerializerOptions.Web) { WriteIndented = true };2) Saving:
File.WriteAllText("settings.json", JsonSerializer.Serialize(settings, options));3) Loading:
Settings loaded = JsonSerializer.Deserialize<Settings>(File.ReadAllText("settings.json"), options)!;4) A record does not change; a new copy is made:
loaded with { FontSize = loaded.FontSize + 2 }, and it is saved again.5) The file:
{ "theme": "dark", "fontSize": 16, "sound": true}Remember
- Build paths with
Path.Combine;Directory.CreateDirectorycreates every level, and theFilehelpers read and write a whole file in one line. - In UTF-8
ətakes 2 bytes; write files in UTF-8 and setConsole.OutputEncoding = Encoding.UTF8for the Windows console. - A
StreamWriterwrites to a buffer: withoutusing(orawait using) the data may never reach the file. - Catch exceptions from specific to general:
FileNotFoundException,DirectoryNotFoundException, thenIOException;JsonExceptionis for bad JSON. System.Text.Jsondefaults to PascalCase and\u0259;JsonSerializerOptions.Web,WriteIndentedand an encoder withUnicodeRanges.Allgive readable output.- Save important files to a temporary file first and then replace them with
File.Move(..., overwrite: true).