Files and JSON
Almost every app reads and writes files and exchanges JSON. This video covers the File class and streams for small and big files, and System.Text.Json: why a JSON file with data can give an empty object, how options and attributes control mapping, JSON straight to streams, and source generation.
36.1 Why is it used?
- Config, exports, logs and caches live in files; APIs and storage exchange data as JSON.
- System.Text.Json is built into .NET, fast, and the default serializer in ASP.NET Core.
- Choosing the right file API matters: ReadAll methods load everything into memory, streams read piece by piece.
- Wrong serializer settings fail silently: unmatched properties just stay at their default values.
36.2 The bug: JSON has data, object is empty
- order.json holds id 101, customer Priya, but the record comes out Id 0, empty Customer, Total 0, with no error.
C#
using System.Text.Json; var json = await File.ReadAllTextAsync( "order.json");var order = JsonSerializer .Deserialize<Order>(json); Console.WriteLine($"Id: {order!.Id}");Console.WriteLine($"Customer: {order.Customer}");Console.WriteLine($"Total: {order.Total}"); public record Order( int Id, string Customer, decimal Total);Output
$ dotnet runId: 0Customer:Total: 0- Step 1
1.JSON has "id": camelCase
- Step 2
2.C# property is Id: PascalCase
- Step 3
3.Default matching is case sensitive
- Step 4
4.No match: property silently ignored
- Step 5
5.Id stays 0, Customer empty, Total 0
Fix: give the serializer options
36.3 File class: small files
- Path.Combine builds paths with the right separator on Windows and Linux.
- Directory.CreateDirectory creates the folder (no error if it exists).
- WriteAllLinesAsync writes, AppendAllLinesAsync adds lines, ReadAllLinesAsync returns all lines as an array.
- ReadAllTextAsync / WriteAllTextAsync do the same for a single string.
C#
var folder = Path.Combine("data", "notes");Directory.CreateDirectory(folder);var path = Path.Combine(folder, "todo.txt"); await File.WriteAllLinesAsync(path, ["Buy milk", "Pay electricity bill"]);await File.AppendAllLinesAsync(path, ["Book train ticket"]); var lines = await File.ReadAllLinesAsync(path);Console.WriteLine($"Path: {path}");Console.WriteLine($"Lines: {lines.Length}");Console.WriteLine($"Last: {lines[^1]}");Output
$ dotnet runPath: data\notes\todo.txtLines: 3Last: Book train ticket36.4 Big files: StreamReader
- ReadAll methods load the whole file into memory; fine for small files only.
- StreamReader opens the file as a stream and ReadLineAsync returns one line at a time until the end (null).
- 2-million-line app.log: peak memory 36 MB with StreamReader vs 425 MB with ReadAllLinesAsync.
C#
using System.Diagnostics; int total = 0, errors = 0;using var reader = new StreamReader("app.log"); while (await reader.ReadLineAsync() is { } line){ total++; if (line.Contains("ERROR")) errors++;}var peak = Process.GetCurrentProcess() .PeakWorkingSet64 / 1_000_000;Console.WriteLine($"Lines: {total:N0}");Console.WriteLine($"Errors: {errors:N0}");Console.WriteLine($"Peak memory: {peak} MB");Output
# app.log: 145 MB, 2 million lines$ dotnet runLines: 2,000,000Errors: 40,000Peak memory: 36 MB# ReadAllLinesAsync: Peak memory: 425 MB36.5 Fix: JsonSerializerOptions with Web defaults
- JsonSerializerDefaults.Web = camelCase names, case-insensitive matching, numbers allowed in quotes: the rules web APIs follow.
- Pass the options to Deserialize: now Id = 101, Customer = Priya.
- The same options serialize back to camelCase JSON.
- Create options once and reuse them; JsonSerializerOptions.Web is a ready-made read-only instance.
C#
using System.Text.Json; var options = new JsonSerializerOptions( JsonSerializerDefaults.Web);var json = await File.ReadAllTextAsync( "order.json");var order = JsonSerializer .Deserialize<Order>(json, options)!; Console.WriteLine(order);Console.WriteLine( JsonSerializer.Serialize(order, options)); public record Order( int Id, string Customer, decimal Total);Output
$ dotnet runOrder { Id = 101, Customer = Priya, Total = 1499.50 }{"id":101,"customer":"Priya","total":1499.50}36.6 Attributes: per-property rules
| Attribute | Effect |
|---|---|
| [JsonPropertyName("full_name")] | Uses a different JSON name for this property |
| [JsonIgnore] | Never serialized (e.g. Password) |
| [JsonIgnore(Condition = WhenWritingNull)] | Skipped only when the value is null |
| [JsonConverter(typeof(JsonStringEnumConverter))] | Enum written by name ("Premium") instead of a number |
| required (C# keyword) | Deserialize throws JsonException if missing |
C#
using System.Text.Json.Serialization; public class User{ [JsonPropertyName("full_name")] public string Name { get; set; } = ""; [JsonIgnore] public string Password { get; set; } = ""; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Phone { get; set; } public Plan Plan { get; set; }}[JsonConverter(typeof(JsonStringEnumConverter))]public enum Plan { Free, Premium }Output
# Serialize(user, JsonSerializerOptions.Web)$ dotnet run{"full_name":"Rahul Sharma","plan":"Premium"}36.7 JSON straight into a stream
- File.Create gives a FileStream; SerializeAsync writes the object straight into it, no big string in between.
- File.OpenRead + DeserializeAsync read it back; the same pattern works for HTTP bodies.
- await using flushes and closes the stream.
C#
using System.Text.Json;var web = JsonSerializerOptions.Web;var cart = new Cart("Priya", [new("Mixer Grinder", 2499), new("Steel Bottle", 399)]); await using (var file = File.Create("cart.json")) await JsonSerializer.SerializeAsync( file, cart, web); await using var src = File.OpenRead("cart.json");var saved = await JsonSerializer .DeserializeAsync<Cart>(src, web);var total = saved!.Items.Sum(i => i.Price);Console.WriteLine($"{saved.Customer}: {total}");Output
$ dotnet runPriya: 2898- Step 1
1.C# object (Order, Cart)
- Step 2
2.Serializer reads options + attributes
- Step 3
3.Names and values decided (camelCase, enums, ignore)
- Step 4
4.Converted to JSON text or UTF-8 bytes
- Step 5
5.Written to a file, stream or HTTP response
Deserialize: same steps in reverse
36.8 Checkpoint: required property missing
- Id is required but the JSON has only customer, so Deserialize throws JsonException.
- Total is also missing but not required, so it would just stay 0.
C#
using System.Text.Json; var json = """{ "customer": "Priya" }""";var order = JsonSerializer.Deserialize<Order>( json, JsonSerializerOptions.Web);Console.WriteLine(order!.Total); public class Order{ public required int Id { get; set; } public string Customer { get; set; } = ""; public decimal Total { get; set; }}Output
$ dotnet runUnhandled exception. System.Text.Json.JsonException:JSON deserialization for type 'Order' was missingrequired properties including: 'id'.36.9 Source generation: no reflection
- By default the serializer inspects types with reflection at runtime: slow first call, problems with Native AOT and trimming.
- Source generation creates that code at build time.
- [JsonSerializable(typeof(Order))] on a partial class deriving from JsonSerializerContext; options via [JsonSourceGenerationOptions].
- Pass AppJsonContext.Default.Order to Serialize; the output is the same camelCase JSON.
C#
using System.Text.Json;using System.Text.Json.Serialization; var order = new Order(101, "Priya", 1499.50m);var json = JsonSerializer.Serialize( order, AppJsonContext.Default.Order);Console.WriteLine(json); public record Order( int Id, string Customer, decimal Total);[JsonSourceGenerationOptions( JsonSerializerDefaults.Web)][JsonSerializable(typeof(Order))]public partial class AppJsonContext : JsonSerializerContext;Output
$ dotnet run{"id":101,"customer":"Priya","total":1499.50}36.10 Common mistakes
- Forgetting the Web defaults (or PropertyNameCaseInsensitive) for camelCase JSON: silent zeros and nulls.
- Not disposing a stream: the file stays locked (IOException) and data stays in the buffer.
- Creating new JsonSerializerOptions on every call instead of reusing one instance.
- Reading huge files with ReadAllLines instead of a stream.
- Myth: you need Newtonsoft.Json. System.Text.Json is built in and the first choice for new code; Newtonsoft is mostly in older code.
C#
var file = File.Create("report.txt");var writer = new StreamWriter(file);writer.WriteLine("Total: 2898"); var text = File.ReadAllText("report.txt");Console.WriteLine(text); // IOException: The process cannot access// the file ... because it is being used// by another process.C#
using (var w = new StreamWriter("report.txt")){ w.WriteLine("Total: 2898");} var text = File.ReadAllText("report.txt");Console.WriteLine(text); // Total: 289836.11 Comparison: file APIs
| API | Reads | Best for |
|---|---|---|
| File.ReadAllTextAsync / ReadAllLinesAsync | Whole file into memory | Small files, config |
| StreamReader.ReadLineAsync | One line at a time | Big logs, CSVs |
| File.Create / OpenRead + SerializeAsync / DeserializeAsync | Stream of bytes | JSON files, HTTP bodies |
36.12 Interview tips
- I use System.Text.Json with Web-default options created once and reused.
- Default matching is case sensitive; unmatched properties are silently ignored.
- Attributes for per-property rules: JsonPropertyName, JsonIgnore, JsonStringEnumConverter.
- Streams (SerializeAsync/DeserializeAsync, StreamReader) for big files and HTTP; always using / await using.
- Source generation with JsonSerializerContext for performance and Native AOT.