Custom Serialization Formatting
This objective covers the use of the BinaryFormatter and SoapFormatter classes. I frankly don’t understand why they should be separated from the rest, with a title of custom serialization, but I guess we should just learn it.
These classes lives in the System.Runtime.Serialization.Formatters namespace. Even better, BinaryFormatter lives in the Binary namespace, and SoapFormatter in the Soap namespace. You will need to set a reference on the System.Runtime.Serialization.Formatters.Soap namespace in order to use the SoapFormatter class. BinaryFormatter is included by default.
BinaryFormatter serializes or deserializes yoir objects into a binary object graph. It will need two things to do so: a stream (not necessary a file stream) and an object, marked as Serializable. By default, all public fields and properties are serialized (and private fields with public properties). You can override this setting by mark your fields with the NonSerializable or OptionalField attribute. The latter is useful when dealing with version-compatible serialization.
A basic example:
public class MyLittleClass
BinaryFormatter bf = new BinaryFormatter();
MyLittleClass myClass = new MyLittleClass();
myClass.x = 32;
myClass.y = “Hello World!”;
And now to deserilaize:
MyLittleClass myC = (MyLittleClass)Bf.Deserialize(File.Open(@”C:\mypath\bin.dat”, FileMode.Open));
//myC.x will be 32, y will be String.Empty
It’s that easy! Note that when an exception occurs during serialization or deserialization, a SerializationException will be thrown. No extra features in it, just the simple Exception.
There’s a method called UnSafeDeserialization. Use it only when you are in full trust security context, otherwise use Deserialization.
Deserialization is dangerous in some cases, due to the so-called deserialization attacks. To evade these attacks, use the FilterLevel property with the Low member of the TypeFilterLevel enumeration.
I bet you could guess the difference between BinaryFormatter and SoapFormatter. Yes, the latter uses the SOAP format, which is cool when dealing with remote procedure calls, and provides vast compatibility between systems, languages, etc.
Because of the nature of SOAP, SoapFormatter don’t provide unsafe deserialization methods. Otherwise the use and feel is same as the BinaryFormatter’s.