44 lines
1.4 KiB
C#
44 lines
1.4 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using SharepointToolbox.Web.Core.Models;
|
|
|
|
namespace SharepointToolbox.Web.Infrastructure.Persistence;
|
|
|
|
public class SettingsRepository
|
|
{
|
|
private readonly string _filePath;
|
|
private readonly SemaphoreSlim _writeLock = new(1, 1);
|
|
|
|
public SettingsRepository(string filePath) { _filePath = filePath; }
|
|
|
|
public async Task<AppSettings> LoadAsync()
|
|
{
|
|
if (!File.Exists(_filePath)) return new AppSettings();
|
|
try
|
|
{
|
|
var json = await File.ReadAllTextAsync(_filePath, Encoding.UTF8);
|
|
return JsonSerializer.Deserialize<AppSettings>(json,
|
|
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new AppSettings();
|
|
}
|
|
catch { return new AppSettings(); }
|
|
}
|
|
|
|
public async Task SaveAsync(AppSettings settings)
|
|
{
|
|
await _writeLock.WaitAsync();
|
|
try
|
|
{
|
|
var json = JsonSerializer.Serialize(settings, new JsonSerializerOptions
|
|
{
|
|
WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
|
});
|
|
var dir = Path.GetDirectoryName(_filePath);
|
|
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
|
var tmp = _filePath + ".tmp";
|
|
await File.WriteAllTextAsync(tmp, json, Encoding.UTF8);
|
|
File.Move(tmp, _filePath, overwrite: true);
|
|
}
|
|
finally { _writeLock.Release(); }
|
|
}
|
|
}
|