Independent assembly serialization in .NET

I use serialization / deserialization method. Class BinaryFormatter. Each time a new assembly is created, BinaryFormatter cannot deserialize binary data, even if the class structure is the same, but the version of the assembly is different. Is it possible to deserialize a binary buffer without checking the assembly version if the class structure remains unchanged?

+8
c # deserialization binaryformatter
source share
3 answers

Try the following:

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); 

Added:

Yes it works. Just make sure that there are any types of System.Generic or other Libs in the binary data, then you must pass them unchanged. "ResizableControls" is the name of the old lib assembly, "EntityLib" is the new assembly name. In addition, the version number must also be replaced upon request.

 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)); } } 

Thank you, this is exactly what I need.

+7
source share

This is inherent in the BinaryFormatter . There are some advanced things you can do to get around this (with surrogates, etc.), but it is not easy, and I honestly do not recommend it.

I highly recommend you look at contract based serializer; eg:

  • XmlSerializer
  • DataContractSerializer (but not NetDataContractSerializer )
  • Protobuf network

(I tend to be the latter, as it gives a much more efficient result and deliberately avoids a few more version issues)

In all these cases, the data warehouse (at least with the default settings) does not contain any type knowledge, except for the contract implied by names, or as indicated (usually in attributes).

+6
source share

I think this is a problem with BinaryFormatter - here - this is a possible solution you can control the type for loading using SerializationBinder - the link provides code and an example of how to use this (in almost all .net languages)

+1
source share

All Articles