G
Guest
How can I serialize/deserialize an object into a string. Existing examples
seem to be showing this operation for files only.
Thansk
seem to be showing this operation for files only.
Thansk
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
Val said:How can I serialize/deserialize an object into a string. Existing examples
seem to be showing this operation for files only.
Peter Bromberg said:What you are really asking is how to convert a stream (e.g. MemoryStream) to
a string. If you are using the BinaryFormatter the MemoryStream you serialize
to or from can be converted to / from a string as follows:
Stream to string:
byte[] b = MyMemoryStream.ToArray();
string s = System.Text.Encoding.UTF8.GetString(b);
String to stream:
string s = "whatever";
byte[] b = System.Text.Encoding.UTF8.GetBytes(s);
MemoryStream ms = new MemoryStream(b);
Jon Skeet said:Peter Bromberg said:What you are really asking is how to convert a stream (e.g. MemoryStream) to
a string. If you are using the BinaryFormatter the MemoryStream you serialize
to or from can be converted to / from a string as follows:
Stream to string:
byte[] b = MyMemoryStream.ToArray();
string s = System.Text.Encoding.UTF8.GetString(b);
String to stream:
string s = "whatever";
byte[] b = System.Text.Encoding.UTF8.GetBytes(s);
MemoryStream ms = new MemoryStream(b);
That's a way which is almost guaranteed to lose data. Serialization
with BinaryFormatter produces opaque binary data, which may very well
not be a valid UTF-8 encoded string.
To convert arbitrary binary data to a string and back, I'd use
Convert.ToBase64String and Convert.FromBase64String.
Jon Skeet said:Peter Bromberg said:What you are really asking is how to convert a stream (e.g. MemoryStream) to
a string. If you are using the BinaryFormatter the MemoryStream you serialize
to or from can be converted to / from a string as follows:
Stream to string:
byte[] b = MyMemoryStream.ToArray();
string s = System.Text.Encoding.UTF8.GetString(b);
String to stream:
string s = "whatever";
byte[] b = System.Text.Encoding.UTF8.GetBytes(s);
MemoryStream ms = new MemoryStream(b);
That's a way which is almost guaranteed to lose data. Serialization
with BinaryFormatter produces opaque binary data, which may very well
not be a valid UTF-8 encoded string.
To convert arbitrary binary data to a string and back, I'd use
Convert.ToBase64String and Convert.FromBase64String.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.