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

1

5

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?

Jaleesa answered 6/9, 2014 at 14:53 Comment(1)
there are other binary serializers which are class-culture-assembly agnostic. ProtoBuf-net is one, and I think NetSerializer on CodeProject is as well.Veliavelick
G
9

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.

Gilbye answered 6/9, 2014 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.