78 lines
2.5 KiB
C#
78 lines
2.5 KiB
C#
using RhythmBullet.Zer01HD.Preferences;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Xml.Serialization;
|
|
|
|
namespace RhythmBullet.Zer01HD.Utilities.Persistence
|
|
{
|
|
public class PreferencesManager
|
|
{
|
|
private readonly Dictionary<Type, Preferences> preferenceList;
|
|
string savePath;
|
|
XmlSerializer xmlSerializer;
|
|
|
|
public PreferencesManager(string savePath, params Preferences[] preferences)
|
|
{
|
|
this.savePath = savePath;
|
|
Directory.CreateDirectory(savePath);
|
|
preferenceList = new Dictionary<Type, Preferences>();
|
|
Debug.WriteLine("Preference manager setting up...");
|
|
Type[] preferenceTypes = new Type[preferences.Length];
|
|
for (int prefID = 0; prefID < preferences.Length; prefID++)
|
|
{
|
|
preferenceList.Add(preferences[prefID].GetType(), preferences[prefID]);
|
|
preferenceTypes[prefID] = preferences[prefID].GetType();
|
|
Debug.WriteLine(preferences[prefID] + " added to list of preferences");
|
|
}
|
|
|
|
xmlSerializer = new XmlSerializer(typeof(Preferences), preferenceTypes);
|
|
}
|
|
|
|
public T GetPreferences<T>() where T : Preferences
|
|
{
|
|
return (T)preferenceList[typeof(T)];
|
|
}
|
|
|
|
public void Load()
|
|
{
|
|
foreach (KeyValuePair<Type, Preferences> prefs in preferenceList)
|
|
{
|
|
if (!LoadSpecific(prefs.Key))
|
|
{
|
|
SaveSpecific(prefs.Key);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Save()
|
|
{
|
|
foreach (KeyValuePair<Type, Preferences> prefs in preferenceList)
|
|
{
|
|
SaveSpecific(prefs.Key);
|
|
}
|
|
}
|
|
|
|
private bool LoadSpecific(Type preference)
|
|
{
|
|
string path = savePath + "/" + preference.Name;
|
|
if (File.Exists(path))
|
|
{
|
|
Stream stream = new FileStream(savePath + "/" + preference.Name + ".xml", FileMode.Open);
|
|
preferenceList[preference] = (Preferences)xmlSerializer.Deserialize(stream);
|
|
stream.Close();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private void SaveSpecific(Type preference)
|
|
{
|
|
Stream stream = new FileStream(savePath + "/" + preference.Name + ".xml", FileMode.Create);
|
|
xmlSerializer.Serialize(stream, preferenceList[preference]);
|
|
stream.Close();
|
|
}
|
|
}
|
|
}
|