Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't deserialize with binaryFormatter after changing namespace of class

After changing the namespace of my class I can no longer deserialize the objects. I've implemented SerializationBinder. Example:

public class TypeNameConverter : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        typeName = typeName.Replace("MyOldNamespace", "MyNewNamespace");
        return Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
    }
}

BinaryFormatter bf = new BinaryFormatter();
bf.Binder = new TypeNameConverter();

The exception I get is:

'System.Runtime.Serialization.TypeLoadExceptionHolder' cannot be converted to type 'MyNewNamespace.MyClass'

like image 906
Max Eisenhardt Avatar asked Oct 04 '12 23:10

Max Eisenhardt


1 Answers

you forgot to replace the assembly name:

class TypeNameConverter : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        typeName = typeName.Replace("MyOldNamespace", "MyNewNamespace");
        assemblyName = assemblyName.Replace("MyOldNamespace", "MyNewNamespace");
        return Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
    }
}
like image 146
Bastianon Massimo Avatar answered Sep 29 '22 13:09

Bastianon Massimo