Skip to content

Commit

Permalink
#137 use application data folder if saving setting file fails
Browse files Browse the repository at this point in the history
  • Loading branch information
Ruben2776 committed Feb 8, 2024
1 parent 4c8d5fb commit 8c77a3d
Showing 1 changed file with 36 additions and 6 deletions.
42 changes: 36 additions & 6 deletions src/PicView.Core/Config/SettingsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ namespace PicView.Core.Config;

[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(AppSettings))]
internal partial class SourceGenerationContext : JsonSerializerContext
{
}
internal partial class SourceGenerationContext : JsonSerializerContext;

public static class SettingsHelper
{
Expand All @@ -34,9 +32,21 @@ public static async Task LoadSettingsAsync()
}
else
{
SetDefaults();
// Get the default culture from the OS
Settings.UIProperties.UserLanguage = CultureInfo.CurrentCulture.Name;
var appData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Ruben2776/PicView/Config/UserSettings.json");
if (File.Exists(appData))
{
var jsonString = await File.ReadAllTextAsync(appData).ConfigureAwait(false);
var settings = JsonSerializer.Deserialize(
jsonString, typeof(AppSettings), SourceGenerationContext.Default)
as AppSettings;
Settings = await UpgradeSettings(settings).ConfigureAwait(false);
}
else
{
SetDefaults();
// Get the default culture from the OS
Settings.UIProperties.UserLanguage = CultureInfo.CurrentCulture.Name;
}
}
}
catch (Exception ex)
Expand Down Expand Up @@ -72,6 +82,14 @@ private static void InitiateJson()
};
}

private static async Task PerformSave(string path)
{
var updatedJson = JsonSerializer.Serialize(
Settings, typeof(AppSettings), SourceGenerationContext.Default);
await using var writer = new StreamWriter(path);
await writer.WriteAsync(updatedJson).ConfigureAwait(false);
}

public static async Task SaveSettingsAsync()
{
InitiateJson();
Expand All @@ -83,6 +101,18 @@ public static async Task SaveSettingsAsync()
await using var writer = new StreamWriter(path);
await writer.WriteAsync(updatedJson).ConfigureAwait(false);
}
catch (UnauthorizedAccessException ex)
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Ruben2776/PicView/Config/UserSettings.json");
try
{
await PerformSave(path).ConfigureAwait(false);
}
catch (Exception)
{
Trace.WriteLine($"{nameof(SaveSettingsAsync)} error saving settings:\n {ex.Message}");
}
}
catch (Exception ex)
{
Trace.WriteLine($"{nameof(SaveSettingsAsync)} error saving settings:\n {ex.Message}");
Expand Down

0 comments on commit 8c77a3d

Please sign in to comment.