views:

75

answers:

2

Basically I want MyObject to be serialized into a string using Binary Serialization.

Is this possible? If so, how to do this? Same for deserialization, from string to MyObject.

+2  A: 

I want MyObject to be serialized into a string using Binary Serialization

This is kind of contradictory, but you can grab the bytes from a (Memory)Stream and convert them to text. Your string will not be very 'readable' of course. If you want it to be able to go round-trip you have to carefully choose encoding.

string text = Convert.ToBase64String(strm.ToArray());  // corrected

And later

byte[] binary = Convert.FromBase64String(text);
var strm2 = new System.IO.MemoryStream(binary);
Henk Holterman
Thanks, can you please post an example? So first way, you use ToString(), the other way around, how do I specify the encoding?
Joan Venge
Certainly not `ToString`, and no `Encoding.GetString` either.
Henk Holterman
`GetBuffer` returns an over-sized array. You need `ToArray`, or you need to specify the `Length`. Otherwise you are storing the wrong data.
Marc Gravell
OK Marc, thanks. Corrected.
Henk Holterman
+2  A: 

There are two easy approaches you could take here, either should work just fine.

  1. Use XmlSerializer to serialize it to XML instead of serializing to binary.

  2. Serialize to binary and use the Convert.ToBase64String() and Convert.FromBase64String() methods to convert to/from binary/string formats.

Eric Petroelje
Using a MemoryStream?
Joan Venge
Joan, the `MemoryStream` is convenient here but any other stream would do as well.
Henk Holterman
Thanks Henk, I will use MS then.
Joan Venge