Skip to content

Commit

Permalink
Use StreanWriter #137
Browse files Browse the repository at this point in the history
  • Loading branch information
Ruben2776 committed Jan 23, 2024
1 parent f4d639e commit 27b6d3d
Showing 1 changed file with 14 additions and 16 deletions.
30 changes: 14 additions & 16 deletions src/PicView.Core/Config/SettingsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 27b6d3d

Please sign in to comment.