Binary Serialization
Binary serialization allows data to be re-contsructed automatically when writing it to the output stream. Here, the necessary information that is required to create an exact binary copy of the object is saved onto the storage media. Binary serialization preserves the entire object state, where XML serialization only saves some of the object data. Another advantage binary serialization has over XML serialization is that it can handle graphs with multiple references to the same object. XML serialization turns each reference into a reference to a unique object. lastly, binary serialization can serialize the read-only properties.
An example below shows how binary serialization can be implemented in C#:
public void BinarySerialize(string filename, Book myBook)
{
FileStream fileStreamObject;
fileStreamObject = new FileStream(filename, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStreamObject, myBook);
fileStreamObject.Close();
}
An example below shows how to implement binary deserialization:
public static object BinaryDeserialize(string filename)
{
FileStream fileStreamObject;
fileStreamObject = new FileStream(filename, FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
return (binaryFormatter.Deserialize(fileStreamObject));
fileStreamObject.Close();
}
A major advantage of using Binary Serialization is that the object can be de-serialized from the same data you serialized it to in the managed environment. Another advantage is its enhanced performance, as it provides support for complex objects, read-only properties, and circular references, although not easily portable to another platform.