Snippet of the day: C#.NET configuration files
17
May0
May0
I’ll start with a longer snippet – handling configuration files in C#.NET. I used this in Windows Touch Remix.
This is the base class I use for my configuration classes:
[Serializable()]
public class XmlConf
{
public static T FromFile<T>(string filename)
{
if (!File.Exists(filename)) return default(T);
XmlSerializer ser = new XmlSerializer(typeof(T));
StreamReader fs = new StreamReader(filename);
T t = (T) ser.Deserialize(fs);
fs.Close();
return t;
}
public void Save(string filename)
{
XmlSerializer ser = new XmlSerializer(this.GetType());
StreamWriter fs = new StreamWriter(filename, false);
ser.Serialize(fs, this);
fs.Close();
}
}
Just subclass it and add your configuration properties:
[Serializable()]
public class MyConf : XmlConf
{
public int IntVal { get; set; }
public string StrVal { get; set; }
}
Make sure you use getters and setters like in the above example, so the values get serialized properly. Most .NET classes (like List) are serializable, but if you have properties of your own class, make sure they are serializable.
Here’s a usage example of saving and loading the configuration:
// Save
MyConf conf = new MyConf();
conf.IntVal = 100;
conf.StrVal = "hey";
conf.Save("my.conf");
// Load
conf = MyConf.FromFile<MyConf>("my.conf");
if (conf == null) new Exception("Configuration file not found.");
Console.WriteLine(conf.IntVal);
Console.WriteLine(conf.StrVal);
No Comments »
No comments yet.