Files
MeWeb/src/MeWeb.App/Services/AppSettings.cs
T

43 lines
1.2 KiB
C#
Raw Normal View History

using System.Text.Json;
namespace MeWeb.App.Services;
public class StoredSettings
{
public string Language { get; set; }
}
public static class AppSettings
{
static readonly string Folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MeWeb");
static readonly string FilePath = Path.Combine(Folder, "settings.json");
public static StoredSettings Read()
{
try
{
if (!File.Exists(FilePath)) return new StoredSettings();
using var stream = File.OpenRead(FilePath);
return JsonSerializer.Deserialize(stream, AppJsonContext.Default.StoredSettings) ?? new StoredSettings();
}
catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
{
return new StoredSettings();
}
}
public static void Write(StoredSettings settings)
{
try
{
Directory.CreateDirectory(Folder);
var temporary = FilePath + ".tmp";
using (var stream = File.Create(temporary))
JsonSerializer.Serialize(stream, settings, AppJsonContext.Default.StoredSettings);
File.Move(temporary, FilePath, overwrite: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
}