From 27b6d3df9fb28af7f594a3936cc238392464f525 Mon Sep 17 00:00:00 2001 From: Ruben Date: Wed, 24 Jan 2024 00:26:59 +0100 Subject: [PATCH] Use StreanWriter #137 --- src/PicView.Core/Config/SettingsHelper.cs | 30 +++++++++++------------ 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/PicView.Core/Config/SettingsHelper.cs b/src/PicView.Core/Config/SettingsHelper.cs index de3e3b7ed..36308883a 100644 --- a/src/PicView.Core/Config/SettingsHelper.cs +++ b/src/PicView.Core/Config/SettingsHelper.cs @@ -20,17 +20,13 @@ public static class SettingsHelper public static async Task LoadSettingsAsync() { + InitiateJson(); try { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config/UserSettings.json"); if (File.Exists(path)) { var jsonString = await File.ReadAllTextAsync(path).ConfigureAwait(false); - _jsonSerializerOptions ??= new JsonSerializerOptions - { - TypeInfoResolver = SourceGenerationContext.Default, - AllowTrailingCommas = true - }; var settings = JsonSerializer.Deserialize( jsonString, typeof(AppSettings), SourceGenerationContext.Default) as AppSettings; @@ -67,19 +63,25 @@ private static void SetDefaults() }; } + private static void InitiateJson() + { + _jsonSerializerOptions ??= new JsonSerializerOptions + { + TypeInfoResolver = SourceGenerationContext.Default, + AllowTrailingCommas = true + }; + } + public static async Task SaveSettingsAsync() { + InitiateJson(); try { - _jsonSerializerOptions ??= new JsonSerializerOptions - { - TypeInfoResolver = SourceGenerationContext.Default, - AllowTrailingCommas = true - }; var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config/UserSettings.json"); var updatedJson = JsonSerializer.Serialize( Settings, typeof(AppSettings), SourceGenerationContext.Default); - await File.WriteAllTextAsync(path, updatedJson).ConfigureAwait(false); + await using var writer = new StreamWriter(path); + await writer.WriteAsync(updatedJson).ConfigureAwait(false); } catch (Exception ex) { @@ -133,11 +135,7 @@ private static async Task SynchronizeSettings(AppSettings settings) } // Save the synchronized settings back to the JSON file - _jsonSerializerOptions ??= new JsonSerializerOptions - { - TypeInfoResolver = SourceGenerationContext.Default, - AllowTrailingCommas = true - }; + InitiateJson(); var updatedJson = JsonSerializer.Serialize( existingSettings, typeof(AppSettings), SourceGenerationContext.Default); await File.WriteAllTextAsync(path, updatedJson).ConfigureAwait(false);