I use Serialization/DeSerialization Technique. BinaryFormatter class. Each time when new assembly is created the BinaryFormatter can't Deserialize binary data even if the class structure is the same, but the Assembly version differs. Is it possible to Deserialize binary buffer with no checking the assembly version if the class structure stays unchanged?
Try this:
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);
Thread Poster Added:
Yes, it works. Just make sure if any types of System.Generic or other Libs in the binary data are present, then you have to pass them through without changes. "ResizableControls" - old Assembly lib' name, "EntityLib" - new Assembly name. Also, the Version number is to be replaced as well, on demand.
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));
}
}
Thanks, it is exactly what I needed.
That is inherent with BinaryFormatter
. There are some advanced things you can do to get around it (with surrogates etc), but it is not easy and I honestly don't recommend it.
I strongly suggest you look at a contract-based serializer; for example:
XmlSerializer
DataContractSerializer
(but notNetDataContractSerializer
)- protobuf-net
(I'm biased towards the last, as it gives a much more efficient output, and deliberately avoids a few more versioning issues)
In all those cases, the data storage does not (at least, with the default settings) include any knowledge of the types, except the contract as implied by the names, or as specified (typically in attributes).
I think that is a know problem with BinaryFormatter - here is a possible solution you can controll which type to load with a SerializationBinder - the link provides code and an example how to use this (in almost all .net languagues)
来源:https://stackoverflow.com/questions/7154046/assembly-independent-serialization-in-net