Search code examples
c#stringserializationbinaryformatter

C# Object Binary Serialization


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?


Solution

  • 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...