Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I renamed a class I am getting a deserialization error. How to fix it?

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?

like image 464
Fred F. Avatar asked Jan 22 '23 08:01

Fred F.


2 Answers

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);
like image 146
user316514 Avatar answered Jan 26 '23 01:01

user316514


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.

like image 42
Marc Gravell Avatar answered Jan 26 '23 01:01

Marc Gravell