rhythmbullet/RhythmBullet/Zer01HD/Utilities/Persistence/PreferencesManager.cs

78 lines
2.4 KiB
C#
Raw Normal View History

2018-10-29 03:42:47 +00:00
using RhythmBullet.Zer01HD.Utilities.Persistence;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace RhythmBullet.Zer01HD.Utilities
{
public class PreferencesManager
{
2018-10-30 23:29:54 +00:00
private readonly Dictionary<Type, Preferences> preferenceList;
2018-10-29 03:42:47 +00:00
public string SavePath;
XmlSerializer xmlSerializer;
2018-10-30 23:29:54 +00:00
public PreferencesManager(string savePath, params Preferences[] preferences)
2018-10-29 03:42:47 +00:00
{
this.SavePath = savePath;
2018-10-30 23:29:54 +00:00
preferenceList = new Dictionary<Type, Preferences>();
Type[] preferenceTypes = new Type[preferences.Length];
for (int prefID = 0; prefID < preferences.Length; prefID++)
2018-10-29 03:42:47 +00:00
{
2018-10-30 23:29:54 +00:00
preferenceList.Add(preferences[prefID].GetType(), preferences[prefID]);
preferenceTypes[prefID] = preferences[prefID].GetType();
2018-10-29 03:42:47 +00:00
}
2018-10-30 23:29:54 +00:00
xmlSerializer = new XmlSerializer(typeof(Preferences), preferenceTypes);
2018-10-29 03:42:47 +00:00
}
2018-10-30 23:29:54 +00:00
public T GetPreferences<T>() where T : Preferences
2018-10-29 03:42:47 +00:00
{
2018-10-30 23:29:54 +00:00
return (T)preferenceList[typeof(T)];
2018-10-29 03:42:47 +00:00
}
public void Load()
{
2018-10-30 23:29:54 +00:00
foreach (KeyValuePair<Type, Preferences> prefs in preferenceList)
2018-10-29 03:42:47 +00:00
{
2018-10-30 23:29:54 +00:00
if (!LoadSpecific(prefs.Key))
{
SaveSpecific(prefs.Key);
}
2018-10-29 03:42:47 +00:00
}
}
public void Save()
{
2018-10-30 23:29:54 +00:00
foreach (KeyValuePair<Type, Preferences> prefs in preferenceList)
{
SaveSpecific(prefs.Key);
}
}
private bool LoadSpecific(Type preference)
{
string path = SavePath + "/" + preference.Name;
if (File.Exists(path))
2018-10-29 03:42:47 +00:00
{
2018-10-30 23:29:54 +00:00
Stream stream = new FileStream(SavePath + "/" + preference.Name, FileMode.Open);
preferenceList[preference] = (Preferences)xmlSerializer.Deserialize(stream);
2018-10-29 03:42:47 +00:00
stream.Close();
2018-10-30 23:29:54 +00:00
return true;
2018-10-29 03:42:47 +00:00
}
2018-10-30 23:29:54 +00:00
return false;
}
private void SaveSpecific(Type preference)
{
Stream stream = new FileStream(SavePath + preference.Name, FileMode.Create);
xmlSerializer.Serialize(stream, preferenceList[preference]);
stream.Close();
2018-10-29 03:42:47 +00:00
}
}
}