Added application session services, along with initial restore and tracker implementations.
This commit is contained in:
47
Harmonia.WinUI/Session/JsonSessionService.cs
Normal file
47
Harmonia.WinUI/Session/JsonSessionService.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user