I am trying to get the BinaryLibrary
value stored in a binary serialization (BinaryFormatter). I've been following outline from here.
I tried a naive:
FileStream fs = new FileStream("binary.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
object obj = formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
Using the debugger I cannot find anything under obj
or formatter
. Where is the BinaryLibrary value stored ? How can I access it ?
The API allows one to register a binder:
So simply register it:
var formatter = new BinaryFormatter();
formatter.Binder = new MyDeserializationBinder();
var obj = formatter.Deserialize(ms);
where definition is:
sealed public class MyDeserializationBinder: SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
typeName, assemblyName));
Console.WriteLine(String.Format("Input is {0}, {1}", typeName, assemblyName));
Console.WriteLine(String.Format("Output is {0}", typeToDeserialize.AssemblyQualifiedName));
return typeToDeserialize;
}
}
Typical outputs:
Input is System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Output is System.Drawing.Point, System.Drawing.Primitives, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
or:
Input is System.Collections.Generic.List`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934
e089
Output is System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral
, PublicKeyToken=7cec85d7bea7798e