I have a project which uses BinaryFormatter to serialize a collection of structs with string and bool? datatypes.
The serialization/deserialization works fine, however if I were to change the assembly which does the work it fails to deserialize because of the header in the binary file indicating that it requires Assembly x
instead of Assembly y
to handle the data.
Is it possible to setup the serialization/deserialization to be assembly agnostic?
So your type can be de-serialized in another assembly, we are setting the assembly-name to " NA " - if you leave the assembly-name as NULL, the normal assembly name will be written into the stream, which is why we set a non- null value (you could use a zero-length string) The BindToType method is essentially the reverse of the BindToName method.
This is the object that is responsible for finding types during serialization and deserialization. To implement your own binder, you derive a new class from the System.Runtime.Serialization.SerializationBinder class, and override the BindToType and BindToName methods:
Try this: declare a separate C# file (call it DataStructure.cs) and move your declaration of the DataStructure class into it (you will have to change the [Serializable] tag to [System.Serializable]). Remove the DataStructure declarations from both the CreateData and ReadData classes. Include the DataStructure.cs file into both projects.
Both define an object called " SimpleObject " in a namespace called " Serialization " - the two objects are identical, but are defined in separate assemblies. One project creates a new instance of a SimpleObject, and serializes it into a file called " example.bin " in the solution directory:
You can control how the binary formatter resolves its types by assigning a custom SerializationBinder to the formatter. In this way, you won't need to mess with the AppDomain's resolve events and you eliminate the risk of unexpected side effects from that.
There is a detailed example at MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With