0

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.

Patrick
  • 3,073
  • 2
  • 22
  • 60
  • 2
    `DataContractSerializer.WriteObject` has an overload that accepts a binary writer, which you aren't using - see https://msdn.microsoft.com/en-us/library/ms752244(v=vs.110).aspx. Serializing data to a binary format is *not* a safe way to store passwords. – Preston Guillot Dec 20 '15 at 22:00
  • Thanks working fine. Why not posting it as a solution? – Patrick Dec 20 '15 at 22:47

1 Answers1

2

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();
}
Dave
  • 473
  • 3
  • 8