Assembly Independent Serialization in .NET

橙三吉。 提交于 2019-11-29 10:19:24
Jacob Seleznev

Try this:

public sealed class CurrentAssemblyDeserializationBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        return Type.GetType(String.Format("{0}, {1}", typeName, Assembly.GetExecutingAssembly().FullName));
    }
}
formatter.Binder = new CurrentAssemblyDeserializationBinder();
formatter.Deserialize(inStream);

Thread Poster Added:

Yes, it works. Just make sure if any types of System.Generic or other Libs in the binary data are present, then you have to pass them through without changes. "ResizableControls" - old Assembly lib' name, "EntityLib" - new Assembly name. Also, the Version number is to be replaced as well, on demand.

public sealed class CurrentAssemblyDeserializationBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        string name;
        if (assemblyName.Contains("ResizableControl"))
        {
            name = Assembly.GetAssembly(typeof(EntityLib.Pattern)).ToString();
        }
        else
        {
            name = assemblyName;
        }
        return Type.GetType(String.Format("{0}, {1}",
            typeName.Replace("ResizableControl", "EntityLib"), name));
    }
}

Thanks, it is exactly what I needed.

That is inherent with BinaryFormatter. There are some advanced things you can do to get around it (with surrogates etc), but it is not easy and I honestly don't recommend it.

I strongly suggest you look at a contract-based serializer; for example:

  • XmlSerializer
  • DataContractSerializer (but not NetDataContractSerializer)
  • protobuf-net

(I'm biased towards the last, as it gives a much more efficient output, and deliberately avoids a few more versioning issues)

In all those cases, the data storage does not (at least, with the default settings) include any knowledge of the types, except the contract as implied by the names, or as specified (typically in attributes).

I think that is a know problem with BinaryFormatter - here is a possible solution you can controll which type to load with a SerializationBinder - the link provides code and an example how to use this (in almost all .net languagues)

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