/// <summary> /// Creates a new, empty JSON settings file /// </summary> /// <param name="filepath">Complete path and file name</param> private static void CreateNewSettingsJson(string filepath) { try { if (!Directory.Exists(Path.GetDirectoryName(filepath))) { _ = Directory.CreateDirectory(Path.GetDirectoryName(filepath)); } File.Create(filepath).Dispose(); const string braces = "{ }"; File.WriteAllText(filepath, braces); } catch (Exception ex) { _ = TKMessageBox.Show($"Error creating settings file.\n{ex}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Writes settings to settings file /// </summary> public static void SaveSettings() { try { JsonSerializerOptions opts = new JsonSerializerOptions { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, WriteIndented = true }; string json = JsonSerializer.Serialize(Setting, opts); File.WriteAllText(FilePath, json); } catch (Exception ex) { _ = TKMessageBox.Show($"Error saving settings file.\n{ex}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Reads settings from a JSON format settings file /// </summary> public static void LoadSettings() { if (File.Exists(FilePath)) { try { Setting = JsonSerializer.Deserialize <T>(File.ReadAllText(FilePath)); } catch (Exception ex) { _ = TKMessageBox.Show($"Error reading settings file.\n{ex}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } else { Setting = new T(); } }