Reputation: 18097
I have such dictionary Dictionary<string, object>
, dictionary holds string keys and objects as values. I need to save and later load such dictionary. What would be best method to do that?
Upvotes: 2
Views: 3321
Reputation: 9654
If you don't mind adding in an extra dependency, you can use protobuf.net. This has the benefit of being fast (definitely faster than the XML serializer approach), and it works on the bog standard Dictionary.
Reference it in your assembly, then the following shows how to use it with a MemoryStream
:
class Program
{
static void Main(string[] args)
{
Dictionary<int, string> dict = new Dictionary<int, string>();
for (int i = 0; i < 10; i++)
{
dict[i] = i.ToString();
}
using (var ms = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(ms, dict);
ms.Seek(0, SeekOrigin.Begin);
var dict2 = ProtoBuf.Serializer.Deserialize<Dictionary<int, string>>(ms);
}
}
}
So long as both the key and value type for the dictionary are serializable by protobuf.net, this will work.
EDIT:
If you want to use this approach, you have to make your key and value object's class serializable by ProtoBuf. In short, attach [ProtoContract]
to the class, and attach e.g. [ProtoMember(1)]
to each Property you want to be serialized. See the website for more details. Note both string
and int
are serializable out of the box.
Upvotes: 0
Reputation: 460078
You can use this serializable Dictionary<TKey, TVal>
(tested):
http://www.dacris.com/blog/2010/07/31/c-serializable-dictionary-a-working-example/
Dictionary<String, Object> otherDictionary = new Dictionary<String, Object>();
otherDictionary.Add("Foo", new List<String>() { "1st Foo","2nd Foo","3rd Foo" });
var dict = new SerializableDictionary<String, Object>(otherDictionary);
write it to a file:
using (FileStream fileStream = new FileStream("test.binary", FileMode.Create))
{
IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(fileStream, dict);
}
read it from a file:
using (FileStream fileStream = new FileStream("test.binary", FileMode.Open))
{
IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
dict = (SerializableDictionary<String, Object>)bf.Deserialize(fileStream);
}
Note: Of course you don't need to create a second Dictionary
. You can use the SerializableDictionary
at the first place. That should just demonstrate how to use it with an already existing Dictionary.
Upvotes: 3
Reputation: 18013
How about serializing it to XML?
http://support.microsoft.com/kb/815813
object yourType = new Object();
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(yourType.GetType());
x.Serialize(Console.Out,yourType);
Upvotes: 0
Reputation: 86
You can use NewtonSoft Json.net: http://james.newtonking.com/projects/json-net.aspx. It is flexible and very friendly.
Upvotes: 0