You could use LINQ2XML to create two methods for writing and reading the Dictionary object.
Storing the Dictionary (extend / change for your types) to a file:
private void storeXml(string location, Dictionary<int, string> data)
{
var xml = new XElement("storage",
data.Select(kv => new XElement("entry",
new XElement("key", kv.Key),
new XElement("value", kv.Value))));
xml.Save(location);
}
Read data from a file and fill the dictionary object:
private Dictionary<int, string> readXml(string location)
{
var data = new Dictionary<int, string>();
var xml = XDocument.Load(location);
foreach(var element in xml.Descendants("entry").ToList())
{
var key = int.Parse(element.Element("key").Value);
var value = element.Element("value").Value;
data.Add(key, value);
}
return data;
}
The code can be used like this:
var data = new Dictionary<int, string>();
data.Add(1, "one");
data.Add(2, "two");
data.Add(3, "three");
data.Add(4, "four");
var fileLocation = @"d:\temp\dictionary.xml";
storeXml(fileLocation, data);
var d = readXml(fileLocation);
The XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<storage>
<entry>
<key>1</key>
<value>one</value>
</entry>
<entry>
<key>2</key>
<value>two</value>
</entry>
<entry>
<key>3</key>
<value>three</value>
</entry>
<entry>
<key>4</key>
<value>four</value>
</entry>
</storage>