Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to recover an object serialized via "BinaryFormatter" after changing class names? [duplicate]

I was using BinaryFormatter to store my application settings. Now, several years into continued development, after many users are already using my application, I want to change how several classes are named and in what namespaces they are located. However, if I do that, it is no longer possible to load the settings, because BinaryFormater calls things by their in-code names.

So, for example, if I change MyNamespace.ClassOne to MyNamespace.Class.NumberOne in code, I can no longer load the settings, because MyNamespace.ClassOne no longer exists.

I'd like to both make this change and allow users retain their settings files. Is this possible?

I mean, I guess I can study the format it's saved in, and manually alter the binary file, substituting class names, but that would be hacker's approach. There must be a normal approach to this, right?

like image 832
Istrebitel Avatar asked Sep 06 '14 14:09

Istrebitel


1 Answers

Yes, it is possible. You can use the SerializationBinder class. Something like this:

public class ClassOneToNumberOneBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        typeName = typeName.Replace(
            "MyNamespace.ClassOne",
            "MyNamespace.Class.NumberOne");

        assemblyName = assemblyName.Replace("MyNamespace", "MyNamespace.Class");

        return Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
    }
}

BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Binder = new ClassOneToNumberOneBinder();

Code example adapted from this answer.

like image 86
BartoszKP Avatar answered Oct 20 '22 12:10

BartoszKP