Last active
December 20, 2015 03:59
-
-
Save AlexArchive/6067343 to your computer and use it in GitHub Desktop.
Settings Base Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class SettingsBase<T> where T : SettingsBase<T>, new() | |
{ | |
protected virtual string SavePath | |
{ | |
get | |
{ | |
return BuildDefaultSavePath(); | |
} | |
} | |
private static T _instance; | |
public static T Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
{ | |
_instance = new T(); | |
_instance = _instance.LoadSettings(); | |
} | |
return _instance; | |
} | |
} | |
public void Save() | |
{ | |
Directory.CreateDirectory(Path.GetDirectoryName(SavePath)); | |
using (var fileStream = new FileStream(SavePath, FileMode.Create)) | |
{ | |
var serializer = new XmlSerializer(typeof(T)); | |
serializer.Serialize(fileStream, this); | |
} | |
} | |
private T LoadSettings() | |
{ | |
if (File.Exists(SavePath) == false) | |
return ResolveDefaultSettings(); | |
try | |
{ | |
using (var fileStream = new FileStream(SavePath, FileMode.Open)) | |
{ | |
var serializer = new XmlSerializer(typeof(T)); | |
var settings = (T)serializer.Deserialize(fileStream); | |
return settings; | |
} | |
} | |
catch (Exception) | |
{ | |
return ResolveDefaultSettings(); | |
} | |
} | |
protected abstract T ResolveDefaultSettings(); | |
private static string BuildDefaultSavePath() | |
{ | |
var applicationDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); | |
var applicationName = Assembly.GetExecutingAssembly().GetName().Name; | |
return Path.Combine(Path.Combine(applicationDataPath, applicationName), "Settings.xml"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment