Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
namespace ConfigManager
{
public class ConfigManager : IDisposable
{
private static readonly XmlSerializer serializer = new XmlSerializer(typeof(Entry[]), new XmlRootAttribute() { ElementName = "Entries" });
private readonly string filepath;
private Dictionary<string, object> items = new Dictionary<string, object>();
public ConfigManager(string filepath)
{
this.filepath = filepath;
if (!File.Exists(filename))
this.Save();
else
this.Load();
}
public T GetWithDefault<T>(string key, T def)
{
object value;
if (!this.items.TryGetValue(key, out value))
{
value = def;
this.items.Add(key, value);
}
return (T)value;
}
public object this[string key]
{
get
{
object value;
this.items.TryGetValue(key, out value);
return value;
}
set
{
this.items[key] = value;
}
}
public void Load()
{
using (var stream = File.OpenRead(this.filepath))
{
this.items = ((Entry[])serializer.Deserialize(stream)).ToDictionary(x => x.Key, x => x.Value);
}
}
public void Save()
{
using (var stream = File.OpenWrite(this.filepath))
{
serializer.Serialize(stream, this.items.Select(x => new Entry() { Key = x.Key, Value = x.Value }).ToArray());
}
}
public void Dispose()
{
this.Save();
}
public class Entry
{
public string Key { get; set; }
public object Value { get; set; }
}
}
}
using System;
using System.IO;
namespace ConfigManager
{
class Program
{
static void Main(string[] args)
{
// Start from a clean slate
File.Delete("test.xml");
using (var configManager = new ConfigManager("test.xml"))
{
// Getting a value which doesn't exist, with a default
int val = (int)configManager.GetWithDefault("test", 5);
Console.WriteLine(val);
}
using (var configManager = new ConfigManager("test.xml"))
{
// Getting a value which does exist, with a default. Demonstrates that the defaulit value was set in the last example
// Also showing that GetWithDefault usage does not require a cast, since it infers the type from the default argument
int val = configManager.GetWithDefault("test", 6);
Console.WriteLine(val);
// Using [] to set a value
configManager["key"] = "value";
}
using (var configManager = new ConfigManager("test.xml"))
{
// Using [] to get a value
string val = (string)configManager["key"];
Console.WriteLine(val);
}
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment