Files and JSON

Work with paths, folders and files, read and write text with streams and asynchronously, keep Azerbaijani letters intact with UTF-8, and save objects as JSON with `System.Text.Json`.

  • Advanced
  • 23 min
  • 12 questions
  • Lesson 13 of 22

In this lesson you will learn

  • Build portable paths with Path and manage folders and files with Directory and File
  • Read and write text with StreamReader/StreamWriter, using and async methods
  • Serialise and deserialise records with System.Text.Json and configure its options
  • Handle I/O and JSON exceptions and keep UTF-8 text intact

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).

C#
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
Run on Windows; on Linux and macOS the separator in the first and fifth lines is /

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.

MethodWhat it does
File.ReadAllText / File.WriteAllTextreads / writes the whole file as one string (old content is replaced)
File.ReadAllLines / File.WriteAllLinesreads / writes an array of lines
File.AppendAllText / File.AppendAllLinesadds to the end of the file and creates it if it does not exist
File.ReadLinesreads lines one by one, on demand — for big files
File.Exists / File.Copy / File.Move / File.Deletecheck, copy, move, delete

Sign up free to keep reading

The rest of the lesson, the quiz and your notes open with an Educora account. Signing up takes a minute, and your progress is saved on all your devices.

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.

C#
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?
5 characters but 7 bytes, and 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.

C#
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 buffer

while ((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:

C#
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 IOException

The 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:

C#
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 asynchronously

File.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.

C#
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"
  ]
}
Serialisation with the default and with tuned options

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.

C#
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.
From JSON to records: letter case does not matter, a missing field becomes null, a wrong type gives a JsonException

Records 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

  1. The model

    record Expense(DateOnly Date, string Category, decimal Amount). DateOnly is written to JSON as "2026-10-01", and decimal is the exact type for money.

  2. Loading

    LoadAsync: no file — an empty list; damaged JSON — a warning and an empty list; otherwise DeserializeAsync reads straight from the file stream.

  3. Safe saving

    AddAsync writes the list to a temporary .tmp file and then replaces the main file with File.Move(..., overwrite: true). If the program crashes in the middle of writing, the old file stays intact.

  4. Trying it out

    Add two expenses, read the file, then damage the file on purpose and make sure that loading does not crash.

C#
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);
    }
}
The ExpenseStore class (at the end of the file)
C#
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 expenses
The start of the program: two expenses, the file contents and a damaged file

Every 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

  • Path builds paths and takes them apart, Directory and File work 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; using flushes the buffer and closes the file.
  • JsonSerializer.Serialize/Deserialize turn an object into JSON and back; JsonSerializerOptions controls 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

1) Open both streams with 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 red
2. Violets are blue
3. C# is fun

Task 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

1) The options, once: 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.CreateDirectory creates every level, and the File helpers read and write a whole file in one line.
  • In UTF-8 ə takes 2 bytes; write files in UTF-8 and set Console.OutputEncoding = Encoding.UTF8 for the Windows console.
  • A StreamWriter writes to a buffer: without using (or await using) the data may never reach the file.
  • Catch exceptions from specific to general: FileNotFoundException, DirectoryNotFoundException, then IOException; JsonException is for bad JSON.
  • System.Text.Json defaults to PascalCase and \u0259; JsonSerializerOptions.Web, WriteIndented and an encoder with UnicodeRanges.All give readable output.
  • Save important files to a temporary file first and then replace them with File.Move(..., overwrite: true).
Spotted a mistake or something inaccurate in this lesson?

Check yourself

12 questions. Every correct answer earns XP.

Question 1 / 12

Question 1 / 12. Which expression builds a path with the right separator for the operating system?