← 返回课程: C# from scratch

Files and JSON: saving and loading data

视频即将上线

Until now, everything your program knew vanished when you closed it. For data to survive (a list of expenses, the settings, the progress of a game) you must save it in a file and read it again next time. In this lesson you will see how to work with text files and, above all, with JSON, a simple text format that almost every language understands, and that .NET can convert to and from your objects with the JsonSerializer class, without installing any additional package.

Text files

The File class offers very handy static methods: WriteAllText creates or replaces a file with a text, AppendAllText adds to the end, ReadAllText reads it entirely, ReadAllLines returns an array with one line per element and File.Exists checks whether it exists. To build paths use Path.Combine, which puts the correct separator on each operating system, and Directory.CreateDirectory to create folders. File operations can fail for many reasons (lack of permissions, full disk, file in use), so it is wise to wrap the access in try/catch with IOException or UnauthorizedAccessException.

csharp
string folder = Path.Combine(Path.GetTempPath(), "csharp-course-demo");
Directory.CreateDirectory(folder);
string path = Path.Combine(folder, "notes.txt");

File.WriteAllText(path, "First line\n");
File.AppendAllText(path, "Second line\n");
Console.WriteLine(File.Exists(path));           // True

foreach (string line in File.ReadAllLines(path))
{
    Console.WriteLine($"> {line}");
}
// > First line
// > Second line

try
{
    string content = File.ReadAllText(Path.Combine(folder, "missing.txt"));
}
catch (FileNotFoundException)
{
    Console.WriteLine("That file does not exist");
}

What JSON is and how to serialize

JSON represents data with objects in braces, lists in brackets and "name": value pairs. Serializing is converting a C# object to JSON text; deserializing is the reverse path. With System.Text.Json it is done with JsonSerializer.Serialize(object) and JsonSerializer.Deserialize<Type>(text). Public properties become fields. With JsonSerializerOptions you can ask for a readable format with WriteIndented = true or change the names of the fields. Records and classes with public properties work without configuration. Deserialize returns a value that may be null, so check the result, and remember that malformed JSON throws JsonException.

csharp
using System.Text.Json;

var tasks = new List<TodoItem>
{
    new(1, "Learn LINQ", true),
    new(2, "Write the project", false),
};

var options = new JsonSerializerOptions { WriteIndented = true };
string json = JsonSerializer.Serialize(tasks, options);
Console.WriteLine(json);
// [
//   { "Id": 1, "Title": "Learn LINQ", "Done": true },
//   { "Id": 2, "Title": "Write the project", "Done": false }
// ]  (printed in several lines)

string file = Path.Combine(Path.GetTempPath(), "todo-demo.json");
File.WriteAllText(file, json);

string text = File.ReadAllText(file);
List<TodoItem>? loaded = JsonSerializer.Deserialize<List<TodoItem>>(text);
Console.WriteLine(loaded?.Count);                       // 2
Console.WriteLine(loaded?[1].Title);                    // Write the project

try
{
    JsonSerializer.Deserialize<List<TodoItem>>("{ this is not json");
}
catch (JsonException)
{
    Console.WriteLine("Invalid JSON");
}

record TodoItem(int Id, string Title, bool Done);

检验所学

第 1 / 2

Which method reads a whole file as a single text?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →