举个例子, 如果在版本1里边序列化了一个文件,后来在版本2里边想进行反序列化,这个时候会抛异常,
"Assemble 1 cannot be cast to Assemble 1.
解决办法,重写SerializationBinder类,把assemblyName改成当前运行的assemblyName。。
sealed class PreMergeToMergedDeserializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type typeToDeserialize = null;
// For each assemblyName/typeName that you want to deserialize to
// a different type, set typeToDeserialize to the desired type.
String exeAssembly = Assembly.GetExecutingAssembly().FullName;
// The following line of code returns the type.
typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
typeName, exeAssembly));
return typeToDeserialize;
}
}
Then when deserializating add this to the BinaryFormatter:
BinaryFormatter bf = new BinaryFormatter();
bf.Binder = new PreMergeToMergedDeserializationBinder();
object obj = bf.Deserialize(ms);