C# Tutorial · Advanced C# · Lesson 21 of 22
C# Files and JSON
Read and write files with File, and serialize JSON with System.Text.Json.
Files
The static File class covers most needs: ReadAllText, WriteAllText, ReadAllLines, AppendAllText, Exists, Delete. Use Path.Combine to build paths.
JSON
System.Text.Json is built in:
using System.Text.Json;
string path = Path.Combine(Path.GetTempPath(), "notes.txt");
File.WriteAllText(path, "first\n");
File.AppendAllLines(path, ["second", "third"]);
string[] lines = File.ReadAllLines(path);
Console.WriteLine($"{lines.Length} lines, last: {lines[^1]}");
File.Delete(path);
Console.WriteLine(File.Exists(path));
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var product = new Product(1, "Mug", 9.5m, ["kitchen"]);
string json = JsonSerializer.Serialize(product, options);
Console.WriteLine(json);
var back = JsonSerializer.Deserialize<Product>("""{"id":2,"name":"Lamp","price":45,"tags":[]}""", options);
Console.WriteLine($"{back!.Name} costs {back.Price}, {back.Tags.Count} tags");
record Product(int Id, string Name, decimal Price, List<string> Tags);
Output
3 lines, last: third
False
{"id":1,"name":"Mug","price":9.5,"tags":["kitchen"]}
Lamp costs 45, 0 tagsRun this on your computer — see “Get Started” for setup.
Test yourself
Which namespace contains the built-in JSON serializer?
Newtonsoft.Json onlySystem.Text.JsonSystem.Json.SerializerMicrosoft.Json
Show answer
Answer: System.Text.Json