I found out that I can use the SerializationInfo
object that comes in the GetObjectData
function, and change the AssemblyName
and FullTypeName
properties, so that when I deserialize I can use a SerializationBinder
to map the custom assembly and type-name back to a valid type. Here is a semple:
Serializable class:
[Serializable]
class MyCustomClass : ISerializable
{
string _field;
void MyCustomClass(SerializationInfo info, StreamingContext context)
{
this._field = info.GetString("PropertyName");
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AssemblyName = "MyCustomAssemblyIdentifier";
info.FullTypeName = "MyCustomTypeIdentifier";
info.AddValue("PropertyName", this._field);
}
}
SerializationBinder:
public class MyBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
if (assemblyName == "MyCustomAssemblyIdentifier")
if (typeName == "MyCustomTypeIdentifier")
return typeof();
return null;
}
}
Serialization code:
var fs = GetStream();
BinaryFormatter f = new BinaryFormatter();
f.Binder = new MyBinder();
var obj = (MyCustomClass)f.Deserialize(fs);
Deserialization code:
var fs = GetStream();
MyCustomClass obj = GetObjectToSerialize();
BinaryFormatter f = new BinaryFormatter();
f.Deserialize(fs, obj);