47 lines
1.2 KiB
C#
47 lines
1.2 KiB
C#
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<ApplicationSession>(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);
|
|
}
|
|
} |