0

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.

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, can you please post an example? So first way, you use ToString(), the other way around, how do I specify the encoding?
Certainly not 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.
2

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.

2 Comments

Joan, the MemoryStream is convenient here but any other stream would do as well.
Thanks Henk, I will use MS then.
0

Xmlserializer does not serialize read only properties and there are other limitations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.