浏览代码

Don't create settings file until serialization

Otherwise you could end up with an empty file and lose all your settings if the JsonTextWriter fails. And good practice to avoid race conditions with the watcher especially.

Uses more memory but the file is so small it's not a reasonable concern.

Potential fix for https://github.com/danielchalmers/DesktopClock/issues/7#issuecomment-1830772175
Daniel Chalmers 1 年之前
父节点
当前提交
f61154ecf8
共有 1 个文件被更改,包括 3 次插入6 次删除
  1. 3 6
      DesktopClock/Properties/Settings.cs

+ 3 - 6
DesktopClock/Properties/Settings.cs

@@ -85,15 +85,12 @@ public sealed class Settings : INotifyPropertyChanged, IDisposable
     #endregion "Properties"
 
     /// <summary>
-    /// Saves to the default path.
+    /// Saves to the default path in JSON format.
     /// </summary>
     public void Save()
     {
-        using var fileStream = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
-        using var streamWriter = new StreamWriter(fileStream);
-        using var jsonWriter = new JsonTextWriter(streamWriter);
-
-        JsonSerializer.Create(_jsonSerializerSettings).Serialize(jsonWriter, this);
+        var json = JsonConvert.SerializeObject(this, _jsonSerializerSettings);
+        File.WriteAllText(FilePath, json);
     }
 
     /// <summary>