How to get BinaryFormatter to deserialize in a different application

大憨熊 提交于 2019-11-30 04:49:49
Sean

The binary serializer encodes class and assembly information into a binary array. When you deserialize this array, the deserializer uses this information to locate the assembly the class resides in, and (if necessary) loads the assembly into you app domain. If the other application doesn't have access to the assembly that the class type resides in then you'll see the error you're getting.

As mentioned by another poster, put these common classes into a shared assembly and deploy them to the client/other application as well as the server application.

If the classes are the same, and it's just another assembly, you could try adding an assemblyBinding section to you .config file.

You should also read the article about Resolving Assembly Loads and the TypeResolve event.

Using these techniques you can redirect the .Net typesystem to another type while deserializing.

Note: Migrating your shared classes to a shared .dll will be a more easy solution.

sealed class PreMergeToMergedDeserializationBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        return Type.GetType("BinarySerialization.YourClass");
    }
}
BinaryFormatter bfDeserialize = new BinaryFormatter();
bfDeserialize.Binder = new PreMergeToMergedDeserializationBinder();
while (fsRead.Position < fsRead.Length)
{
    YourClass sibla = (YourClass)bfDeserialize.Deserialize(fsRead);
}

Assuming you have an exe that serializes data in your "YourClass" and an another exe that de-serializes the YourClass objects.

You cannot!

Best option is to publish your serializable classes in a separate assembly and you refer to it in server (serializer) and client (deserializer). This way you are not publishing the whole of your source code to the outside world.

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