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?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Istrebitel
  • 2,963
  • 6
  • 34
  • 49

1 Answers1

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.

Community
  • 1
  • 1
BartoszKP
  • 34,786
  • 15
  • 102
  • 130