How to get BinaryFormatter to deserialize in a different application

好久不见. 提交于 2019-11-29 00:52:13

问题


I am using BinaryFormatter to serialize an array of class instances to a file. I can deserialize this fine within the same application. When I try the same deserialization in a different application (that pulls in a common file that does the work) then I get the following error:

{"Could not load file or assembly 'pmlscan, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The module was expected to contain an assembly manifest."}

where pmlscan is the name of the original application. How do I get BinaryFormatter to not try and load pmlscan?


回答1:


You can achieve it by using custom SerializationBinder. See here: Advanced Binary Serialization: Deserializing an Object Into a Different Type Than the One It was Serialized Into




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/4193951/how-to-get-binaryformatter-to-deserialize-in-a-different-application

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