I need to serialize/deserialize a class with subclasses in which a member is a dictionary. Another member is a class storing passwords so it can't be XML but binary. Have found that very nice solution which might be easy and issue-free.
http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/
But this example (and all the others I have found) have an xml output which is not the right solution for my problem.
So the question is: "how to make datacontract serialization with binary and not xml output?" Thanx in advance
---ADD--- Even using a filestream with that class:
[DataContract]
public class MyClass
{
// need a parameterless constructor for serialization
public MyClass()
{
MyDictionary = new Dictionary<string, string>();
}
[DataMember]
public Dictionary<string, string> MyDictionary { get; set; }
public int aaaa = 3;
}
and doing
MyClass theclass = new MyClass();
var serializer = new DataContractSerializer(typeof(MyClass));
bool append = true;
using (Stream fileStream = File.Open("aaa.bin", append ? FileMode.Append : FileMode.Create))
{
serializer.WriteObject(fileStream, theclass);
}
the output is XML.
Like Preston Guillot already mentioned in his comment. The DataContractSerializer.WriteObject
also accepts a binary writer. Here is an example just for the sake of completeness.
MyClass theClass = new MyClass();
var serializer = new DataContractSerializer(typeof(MyClass));
bool append = true;
using (Stream fileStream = File.Open("aaa.bin", append ? FileMode.Append : FileMode.Create))
{
XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(fileStream);
serializer.WriteObject(binaryWriter, theClass);
binaryWriter.Flush();
}