Skip to content

Instantly share code, notes, and snippets.

@Kraballa
Last active June 9, 2025 15:52
Show Gist options
  • Save Kraballa/b7bd0578f15c4a45089152b5d53487ce to your computer and use it in GitHub Desktop.
Save Kraballa/b7bd0578f15c4a45089152b5d53487ce to your computer and use it in GitHub Desktop.
Serializer class for serializing and deserializing any dictionary to xml
using System.Xml.Serialization;
namespace Program
{
public static class DictSerializer<K, V> where K : notnull
{
public static void Serialize<T>(T data, string filename) where T : IDictionary<K, V>
{
Tuple<K, V> pair = new();
pair.Keys = data.Keys.ToArray();
pair.Values = data.Values.ToArray();
using (TextWriter writer = new StreamWriter(filename))
{
XmlSerializer serializer = new(typeof(Tuple<K, V>));
serializer.Serialize(writer, pair);
}
}
public static Dictionary<K, V> Deserialize(string filename)
{
object? obj;
using (TextReader reader = new StreamReader(filename))
{
XmlSerializer serializer = new(typeof(Tuple<K, V>));
obj = serializer.Deserialize(reader);
}
if (obj == null)
throw new Exception("error, couldn't deserialize file");
Tuple<K, V> tuple = (Tuple<K, V>)obj;
Dictionary<K, V> dict = new();
for (int i = 0; i < tuple.Keys.Length; i++)
{
dict.Add(tuple.Keys[i], tuple.Values[i]);
}
return dict;
}
}
[Serializable]
public class Tuple<K, V>
{
[XmlArrayItem(ElementName = "Key")]
public K[] Keys;
[XmlArrayItem(ElementName = "Value")]
public V[] Values;
public Tuple()
{
}
}
}
@Kraballa
Copy link
Author

Kraballa commented Jun 9, 2025

usage:

Dictionary<ulong, string> mydict = new();
mydict[1234] = "hello world!";

DictSerializer<ulong, string>.Serialize(mydict, "testfile.txt");

DictSerializer<ulong, string>.Deserialize("testfile.txt);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment