Is it possible to recover an object serialized via “BinaryFormatter” after changing class names?

狂风中的少年 提交于 2019-11-26 17:51:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25701481/is-it-possible-to-recover-an-object-serialized-via-binaryformatter-after-chang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!