Browse Source

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 year ago
parent
commit
f61154ecf8
1 changed files with 3 additions and 6 deletions
  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"
     #endregion "Properties"
 
 
     /// <summary>
     /// <summary>
-    /// Saves to the default path.
+    /// Saves to the default path in JSON format.
     /// </summary>
     /// </summary>
     public void Save()
     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>
     /// <summary>