When I rename the class, I get a deserialization error. How to fix it?

I renamed the classBattle class to Game , and I don’t get "Unable to load the battle.classBattle + udtCartesian type needed for deserialization."

This is a line of code MapSize = (Game.udtCartesian)formatter.Deserialize(fs);

How to fix it? Does this mean that I cannot rename classes?

+4
source share
4 answers

BinaryFormatter is fragile and not intended to be friendly if you have changes in the types used . If you need this type of behavior, you need a contract-based serializer like XmlSerializer , DataContractSerializer or protobuf-net. Everything except BinaryFormatter .

+4
source

You can also use the SerializationBinder to determine which type will be loaded if another type is 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 need to set the Binder property for the BinaryFormatter :

 formatter.Binder = new Version1ToVersion2DeserializationBinder(); NewClassName obj = (NewClassName)formatter.Deserialize(fs); 
+4
source

During serialization, if you do not use contracts, the class name is part of it, so it is quite reasonable that the deserialization of the class name should be the same.

You can change the class name, serialize again and deserialize without problems.

What won't work is serializing with one name and trying to deserialize back to another name.

Otherwise, use the contracts and formatter that uses them.

+1
source

If you are not interested in the saved data, simply delete the file, the new one will be saved using the new name.

0
source

Source: https://habr.com/ru/post/1305873/


All Articles