public static void ChangeSetting(Setting setting, string value) { // Get a temporary file name string tmpFile = Path.GetTempFileName(); // Read the file into the temp file, modifying the setting as we go string line = string.Empty; using (TextReader reader = new StreamReader(settingsFilePath)) { using (TextWriter writer = File.AppendText(tmpFile)) { while ((line = reader.ReadLine()) != null) { if (line.Split('=')[0] == setting.ToString()) // Change this line for the new value writer.WriteLine(setting + "=" + value); else // Write the file as is writer.WriteLine(line); } } } // Replace old file with temp one File.Delete(settingsFilePath); File.Move(tmpFile, settingsFilePath); Load(); // Reload settings }
public static void Save(Setting setting, object value, bool serialize = false) { if (serialize) { value = JsonConvert.SerializeObject(value); } ApplicationData.Current.LocalSettings.Values[setting.ToString()] = value; }
public static T Get <T>(Setting setting, bool deserialize = false) { KeyValuePair <string, object> settingValue = ApplicationData.Current.LocalSettings.Values.FirstOrDefault(v => v.Key == setting.ToString()); object value = null; if (settingValue.Key == null) { value = defaultValueManager.GetDefaultValue(setting); } else { value = settingValue.Value; if (deserialize) { value = JsonConvert.DeserializeObject <T>((string)value); } } return((T)value); }
/// <summary> /// Load a setting from the settings file /// </summary> /// <param name="setting">The setting to load.</param> private static string LoadSetting(Setting setting) { string returnValue = string.Empty; // Create the file if it doesn't exist if (!File.Exists(settingsFilePath)) File.Create(settingsFilePath).Close(); // Read file and return the setting string line = string.Empty; bool foundSetting = false; using (TextReader reader = new StreamReader(settingsFilePath)) while (reader.Peek() >= 0 && !foundSetting) if ((line = reader.ReadLine()).Split('=')[0] == setting.ToString()) foundSetting = true; if(foundSetting) returnValue = line.Split('=')[1]; else { // Setting was not found, so add the default value to the file before returning it returnValue = GetDefaultValue(setting); using (TextWriter writer = File.AppendText(settingsFilePath)) writer.WriteLine(setting + "=" + returnValue); } return returnValue; }