开发者

How to get BinaryFormatter to deserialize in a different application

开发者 https://www.devze.com 2023-01-25 13:54 出处:网络
I am using BinaryFormatter开发者_JAVA技巧 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 differen

I am using BinaryFormatter开发者_JAVA技巧 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?


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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消