I renamed the class classBattle
to Game
and not I get "Unable to load type battle.classBattle+udtCartesian required for deserialization."
This is the line of code MapSize = (Game.udtCartesian)formatter.Deserialize(fs);
How do I fix this? Does this mean I cannot rename classes?
You could also use a SerializationBinder
to define which type will be loaded in the case that another type is being deserialized:
public sealed class Version1ToVersion2DeserializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
Type typeToDeserialize = null;
if (typeName == "OldClassName")
typeName = "NewClassName";
typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
typeName, assemblyName));
return typeToDeserialize;
}
}
To deserialize, you just have to set the Binder
property of the BinaryFormatter
:
formatter.Binder = new Version1ToVersion2DeserializationBinder();
NewClassName obj = (NewClassName)formatter.Deserialize(fs);
BinaryFormatter
is brittle, and is not designed to be friendly if you have changes to the types involved. If you want that type of behaviour, you need a contract-based serializer such as XmlSerializer
, DataContractSerializer
or protobuf-net. Anything except BinaryFormatter
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With