Reputation: 641
I have serialized a class which used to be in namespace Temp, but now I am deserializing inside another namespace (I mean the class which I use to fetch the objects currently resides in another namespace). I am facing the error that the Temp namespace could not be found. I have found this mapping useful: Maintain .NET Serialized data compatability when moving classes.
Is there any way to just serialize the class object and not assembly info or the namespace info? (I am thinking of future change and getting rid of that mapping).
Upvotes: 4
Views: 3742
Reputation: 2246
When you create a BinaryFormatter
to serialize your data, you can set the AssemblyFormat
property to FormatterAssemblyStyle
.Simple. This will cause only the assembly name to be serialized and not the entire version qualified full assembly name.
Also you can use a SerializationBinder
with your BinaryFormatter
. In .NET 4.0 you can provide a BindToName
method as part of the SerializationBinder
that allows you to control custom type name mapping when serializing.
Upvotes: 3
Reputation: 598
You could force the new Type rewriting the method in your own Binder. (http://msdn.microsoft.com/en-us/library/system.runtime.serialization.serializationbinder.aspx)
For example you could define the following class:
sealed class MyBinder : SerializationBinder
{
private readonly Type _type;
public MyBinder(Type type)
{
_type = type;
}
public override Type BindToType(string assemblyName, string typeName)
{
return _type;
}
}
and then set the binder in the BinaryFormatter
var formatter = new BinaryFormatter();
formatter.Binder = new MyBinder(typeof(YourClass));
using (var stream = new MemoryStream(bytes))
{
YourClass yourobject = formatter.Deserialize(stream);
}
Upvotes: 4
Reputation: 117230
The easiest to handle this is with the AppDomain.TypeResolve
event.
Upvotes: 2