using System; using System.IO; using System.Text.Json; using System.Threading.Tasks; namespace Harmonia.WinUI.Session; public sealed class JsonSessionService : ISessionService { private static readonly JsonSerializerOptions Options = new() { WriteIndented = true }; private readonly string _filePath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Harmonia", "session.json" ); public ApplicationSession Session { get; private set; } = new(); public async Task LoadAsync() { try { if (File.Exists(_filePath)) { await using var stream = File.OpenRead(_filePath); Session = await JsonSerializer.DeserializeAsync(stream) ?? new(); } } catch { Session = new(); } } public async Task SaveAsync() { string directoryName = Path.GetDirectoryName(_filePath)!; Directory.CreateDirectory(directoryName); await using var stream = File.Create(_filePath); await JsonSerializer.SerializeAsync(stream, Session, Options); } }