using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace RecrownedGTK.Persistence { /// /// Manages multiple preferences within one file. /// public class Preferences { private Dictionary preferences; string savePath; string fileName; XmlSerializer xmlSerializer; /// /// Constructs the preference manager. /// /// The path of the directory in which the preferences should be saved. /// The preferences to be serialized and unserialized in XML format. public Preferences(string savePath, string fileName) { this.savePath = savePath; this.fileName = fileName; Directory.CreateDirectory(savePath); preferences = new Dictionary(); xmlSerializer = new XmlSerializer(typeof(PreferencesInfo)); } public string GetStringValue(string key) { if (!preferences.ContainsKey(key)) { preferences.Add(key, ""); } return preferences[key]; } public int GetIntValue(string key) { return int.Parse(GetStringValue(key)); } public float GetFloatValue(string key) { return float.Parse(GetStringValue(key)); } public bool GetBoolValue(string key) { return bool.Parse(GetStringValue(key)); } public void SetPreference(string key, string value) { if (preferences.ContainsKey(key)) { preferences[key] = value; } else { preferences.Add(key, value); } } public void SetPreference(string key, int value) { SetPreference(key, value.ToString()); } public void SetPreference(string key, float value) { SetPreference(key, value.ToString()); } public void SetPreference(string key, bool value) { SetPreference(key, value.ToString()); } public bool DeletePreference(string key) { if (!preferences.ContainsKey(key)) return false; preferences.Remove(key); return true; } /// /// Loads preferences. /// public bool Load() { try { using (StreamReader stream = new StreamReader(string.Format("{0}/{1}.xml", savePath, fileName))) { this.preferences = ((PreferencesInfo) xmlSerializer.Deserialize(stream)).GetPreferences(); } } catch (FileNotFoundException) { return false; } return true; } /// /// Saves preferences. /// public void Save() { using (FileStream fileStream = new FileStream(string.Format("{0}/{1}.xml", savePath, fileName), FileMode.Create)) { PreferencesInfo preferences = new PreferencesInfo(); preferences.SetPreferences(this.preferences); xmlSerializer.Serialize(fileStream, preferences); } } } }