浏览代码

Alert user that settings file isn't saveable

#7 ?
Daniel Chalmers 1 年之前
父节点
当前提交
1d8a7b1f68
共有 2 个文件被更改,包括 36 次插入7 次删除
  1. 9 1
      DesktopClock/MainWindow.xaml.cs
  2. 27 6
      DesktopClock/Properties/Settings.cs

+ 9 - 1
DesktopClock/MainWindow.xaml.cs

@@ -272,11 +272,19 @@ public partial class MainWindow : Window
     private void Window_ContentRendered(object sender, EventArgs e)
     {
         SizeChanged += Window_SizeChanged;
+
+        if (!Settings.CanBeSaved)
+        {
+            MessageBox.Show(this,
+                "Settings won't be saved. Make sure you have DesktopClock in a folder that can be written to without administrator privileges!",
+                "Access denied", MessageBoxButton.OK, MessageBoxImage.Warning);
+        }
     }
 
     private void Window_Closed(object sender, EventArgs e)
     {
-        Settings.Default.Save();
+        if (Settings.CanBeSaved)
+            Settings.Default.Save();
 
         App.SetRunOnStartup(Settings.Default.RunOnStartup);
 

+ 27 - 6
DesktopClock/Properties/Settings.cs

@@ -11,7 +11,7 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
 {
     private readonly FileSystemWatcher _watcher;
 
-    private static readonly Lazy<Settings> _default = new(() => Load() ?? new Settings());
+    private static readonly Lazy<Settings> _default = new(LoadAndAttemptSave);
 
     private static readonly JsonSerializerSettings _jsonSerializerSettings = new()
     {
@@ -48,6 +48,8 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
 
     public static string FilePath { get; private set; }
 
+    public static bool CanBeSaved { get; private set; }
+
     #region "Properties"
 
     public string Format { get; set; } = "{dddd}, {MMM dd}, {HH:mm:ss}";
@@ -106,10 +108,7 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
         JsonSerializer.Create(_jsonSerializerSettings).Populate(jsonReader, settings);
     }
 
-    /// <summary>
-    /// Returns loaded settings from the default path or null if it fails.
-    /// </summary>
-    private static Settings Load()
+    private static Settings LoadFromFile()
     {
         try
         {
@@ -119,8 +118,30 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
         }
         catch
         {
-            return null;
+            return new();
+        }
+    }
+
+    private static Settings LoadAndAttemptSave()
+    {
+        var settings = LoadFromFile();
+
+        try
+        {
+            settings.Save();
+
+            CanBeSaved = true;
+        }
+        catch (UnauthorizedAccessException)
+        {
+            CanBeSaved = false;
+        }
+        catch (IOException)
+        {
+            CanBeSaved = false;
         }
+
+        return settings;
     }
 
     private void FileChanged(object sender, FileSystemEventArgs e)