УРОК 12 ИЗ 16
Работа с файлами и JSON
2 Теория
Файлы
using System.IO;
string path = Path.Combine("data", "notes.txt");
Directory.CreateDirectory("data");
File.WriteAllText(path, "первая строка\n");
File.AppendAllText(path, "вторая строка\n");
string[] lines = File.ReadAllLines(path);
foreach (var l in lines) Console.WriteLine(l);
using var reader = new StreamReader(path);
while (await reader.ReadLineAsync() is string line) Console.WriteLine(line); // построчно, экономно по памяти
Console.WriteLine(File.Exists(path));
foreach (var f in Directory.GetFiles("data", "*.txt")) Console.WriteLine(f);
Для путей используйте Path.Combine, а не склейку строк со слешами. using гарантирует закрытие файла.
JSON
using System.Text.Json;
public record Student(string Name, int Age, List<string> Skills);
var s = new Student("Аня", 17, new() { "c#", "sql" });
var options = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
string json = JsonSerializer.Serialize(s, options);
await File.WriteAllTextAsync("student.json", json);
var back = JsonSerializer.Deserialize<Student>(await File.ReadAllTextAsync("student.json"), options);
Console.WriteLine(back?.Name);
using var doc = JsonDocument.Parse(json); // чтение без класса
Console.WriteLine(doc.RootElement.GetProperty("age").GetInt32());
Не десериализуйте непроверенный JSON «вслепую»: проверяйте значения после чтения и ловите JsonException.
