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.
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);
ToString, and no Encoding.GetString either.GetBuffer returns an over-sized array. You need ToArray, or you need to specify the Length. Otherwise you are storing the wrong data.There are two easy approaches you could take here, either should work just fine.
Use XmlSerializer to serialize it to XML instead of serializing to binary.
Serialize to binary and use the Convert.ToBase64String() and Convert.FromBase64String() methods to convert to/from binary/string formats.
MemoryStream is convenient here but any other stream would do as well.