99 lines
3.3 KiB
C#
99 lines
3.3 KiB
C#
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Xml.Serialization;
|
|
|
|
namespace RecrownedGTK.Persistence
|
|
{
|
|
/// <summary>
|
|
/// Manages multiple preferences within one file.
|
|
/// </summary>
|
|
public class Preferences
|
|
{
|
|
private Dictionary<string, string> preferences;
|
|
string savePath;
|
|
string fileName;
|
|
XmlSerializer xmlSerializer;
|
|
|
|
/// <summary>
|
|
/// Constructs the preference manager.
|
|
/// </summary>
|
|
/// <param name="savePath">The path of the directory in which the preferences should be saved.</param>
|
|
/// <param name="preferences">The preferences to be serialized and unserialized in XML format.</param>
|
|
public Preferences(string savePath, string fileName)
|
|
{
|
|
this.savePath = savePath;
|
|
this.fileName = fileName;
|
|
|
|
Directory.CreateDirectory(savePath);
|
|
preferences = new Dictionary<string, string>();
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Loads preferences.
|
|
/// </summary>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Saves preferences.
|
|
/// </summary>
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
}
|