Serialize and deserialize dictionary

Serialize and deserialize dictionary

A few years back i needed to serialize and deserialize a dictionary. The solution turned out to be Adar Wesleys SerializeableDictionary. I can’t find the source blog post by Adar Wesley anymore but only the classes that you need to import into your project. If those files has been deleted as well i have a backup of those files here: serializabledictionary. This is an example on how to do it with C#.

Serialize and deserialize dictionary example

Once the files are included into your project you can use this example to serialize and deserialize a dictionary:

/// <summary>
/// Loads a Serializable dictionary which holds a saved values
/// </summary>
private void LoadExistingFile()
{
    SerializableDictionary<string, int> data = new SerializableDictionary<string, int>();
    if (File.Exists("file.xml"))
    {
        XmlSerializer s = new XmlSerializer(typeof(SerializableDictionary<string, int>));
        using (StreamReader sr = new StreamReader("file.xml"))
        {
            data = s.Deserialize(sr) as SerializableDictionary<string, int>;
        }
    }
}
/// <summary>
/// Saves existing KeyValuePairs to disc
/// </summary>
private void SaveDictionaryToDisc()
{
    SerializableDictionary<string, int> data = new SerializableDictionary<string, int>();
    XmlSerializer s = new XmlSerializer(typeof(SerializableDictionary<string, int>));
    using (StreamWriter sw = new StreamWriter("file.xml"))
    {
        s.Serialize(sw, data);
    }
}

This post is a translation of a blog post that i wrote in Swedish a long time ago. I finally got my thumb out and translated it to English.