using System.Text.Json; namespace Nonemm.Recorder; /// Reads and writes the one configuration file. public sealed class RecorderConfigStore { private static readonly JsonSerializerOptions Options = new() { WriteIndented = true }; private readonly string path; public RecorderConfigStore(string path) { this.path = path; } public static string DefaultPath() { string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(folder, "nonemm-recorder", "config.json"); } /// A missing file gives the default configuration. A file that cannot be /// read throws, so a damaged file is not replaced without the operator /// knowing. public RecorderConfig Load() { if (!File.Exists(path)) { return new RecorderConfig(); } try { using FileStream stream = File.OpenRead(path); return JsonSerializer.Deserialize(stream, Options) ?? new RecorderConfig(); } catch (JsonException cause) { throw new InvalidDataException($"{path} is not a recorder configuration", cause); } } public void Save(RecorderConfig config) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); string temporary = path + ".tmp"; File.WriteAllText(temporary, JsonSerializer.Serialize(config, Options)); File.Move(temporary, path, overwrite: true); } }