views:

445

answers:

4

I want to make a binary serialize of an object and the result to save it in a database.

Person person = new Person();
person.Name = "something";

MemoryStream memorystream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(memorystream, person);

How can I transform memorystream in a string type to be saved in database, and after this to be able to deserialize the object?

Thanks!

+5  A: 

What you're really asking for is a safe way of representing arbitrary binary data as text and then converting it back again. The fact that it stores a serialized object is irrelevant.

The answer is almost to use Base 64 (e.g. Convert.ToBase64String and Convert.FromBase64String). Do not use Encoding.UTF8.GetString or anything similar - your binary data is not encoded text data, and shouldn't be treated as such.

However, does your database not have a data type for binary data? Check for BLOB, IMAGE and BINARY types...

Jon Skeet
+2  A: 

I used something like this

MemoryStream memoryStream = new MemoryStream();
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, Person);
                memoryStream.Flush();
                memoryStream.Position = 0;
                string value = Convert.ToBase64String(memoryStream.ToArray());
astander
You don't need to rewind a MemoryStream before calling ToArray - it returns the whole stream's data regardless of the current position. Likewise Flush doesn't do anything on a MemoryStream, although it's a good idea for streams in general.
Jon Skeet
Thanx for the advise.
astander
+1  A: 

Basically, don't save the data as string to the database, there are blob fields available to store binary data.

If you really need to have the data as string, you'll need to convert your byte[] to a string using base64 encoding, and to grab the byte[] from a string use decoding.

Jan Jongboom
A: 

Have you not looked into converting the memorystream into a base64hex string to be put into the database?

 byte[] mStream = memorystream.ToArray();
 string sConvertdHex = System.Convert.ToBase64String(mStream)

Then you can dump the contents sConvertdHex to the database. To deserialize it you need to do the reverse

 byte[] mData = System.Convert.FromBase64String(...)

then deserialize mData back to your object.

tommieb75