public static SettingCollection LoadSettingsFromFile() { SettingCollection settings; var file = GetSettingsFilePath(); try { if (!File.Exists(file)) { settings = new SettingCollection(); Console.WriteLine("Settings file not found: " + file); } else { var settingsString = File.ReadAllText(file); settings = FromJson(settingsString); } } catch { Console.WriteLine("Error loading settings from " + SettingSubFolderName); BackupMalformedSettingsFile(); settings = new SettingCollection(); } ExceptionLogger.SetSettingsContext(settings); WriteSettingsToFile(settings); // write to file to ensure any missing settings are added with defaults return(settings); }
public static void WriteSettingsToFile(SettingCollection settings) { ExceptionLogger.SetSettingsContext(settings); try { var jsonSettings = ToJson(settings, true); var filename = GetSettingsFilePath(); File.WriteAllText(filename, jsonSettings); Console.WriteLine($"Writing settings as: {jsonSettings}"); } catch (Exception e) { Console.WriteLine($"Error writing settings: {e}"); } }
internal static SettingCollection FromJson(string json) { try { var settings = new SettingCollection(); JsonConvert.PopulateObject(json, settings, new JsonSerializerSettings { ContractResolver = new JsonSettingsContractResolver() }); ExceptionLogger.SetSettingsContext(settings); return(settings); } catch { Console.WriteLine("Error loading settings from " + json); BackupMalformedSettingsFile(); return(new SettingCollection()); } }
internal static string ToJson(SettingCollection settings, bool intended) => JsonConvert.SerializeObject(settings, intended ? Formatting.Indented : Formatting.None);