BizHawk/BizHawk.Client.Common/config/ConfigService.cs

75 lines
2.1 KiB
C#
Raw Normal View History

2013-10-25 00:59:34 +00:00
using System;
using System.IO;
using System.Reflection;
using Newtonsoft.Json;
namespace BizHawk.Client.Common
{
public static class ConfigService
{
public static T Load<T>(string filepath, T currentConfig) where T : new()
{
T config = new T();
try
{
var file = new FileInfo(filepath);
if (file.Exists)
using (var reader = file.OpenText())
{
var s = new JsonSerializer
{
MissingMemberHandling = MissingMemberHandling.Ignore,
TypeNameHandling = TypeNameHandling.Auto
//SuppressDuplicateMemberException = true
};
var r = new JsonTextReader(reader);
2013-10-25 00:59:34 +00:00
config = (T)s.Deserialize(r, typeof(T));
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Config Error", ex);
}
//if (config == null) return new T();
2013-10-25 00:59:34 +00:00
//patch up arrays in the config with the minimum number of things
// TODO: do we still need this with the new json.net version?
2013-10-25 00:59:34 +00:00
foreach(var fi in typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public))
if (fi.FieldType.IsArray)
{
Array aold = fi.GetValue(currentConfig) as Array;
Array anew = fi.GetValue(config) as Array;
if (aold.Length == anew.Length) continue;
//create an array of the right size
Array acreate = Array.CreateInstance(fi.FieldType.GetElementType(), Math.Max(aold.Length,anew.Length));
//copy the old values in, (presumably the defaults), and then copy the new ones on top
Array.Copy(aold, acreate, Math.Min(aold.Length,acreate.Length));
Array.Copy(anew, acreate, Math.Min(anew.Length, acreate.Length));
//stash it into the config struct
fi.SetValue(config, acreate);
}
return config;
}
public static void Save(string filepath, object config)
{
var file = new FileInfo(filepath);
using (var writer = file.CreateText())
{
var s = new JsonSerializer
{
TypeNameHandling = TypeNameHandling.Auto
};
var w = new JsonTextWriter(writer) { Formatting = Formatting.Indented };
2013-10-25 00:59:34 +00:00
s.Serialize(w, config);
}
}
}
}