3

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

Community
  • 1
  • 1
Yasser Sobhdel
  • 611
  • 8
  • 26

3 Answers3

4

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);
}
Jaime Marín
  • 578
  • 6
  • 11
3

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.

Jaime Marín
  • 578
  • 6
  • 11
tbergelt
  • 2,196
  • 1
  • 14
  • 5
2

The easiest to handle this is with the AppDomain.TypeResolve event.

leppie
  • 115,091
  • 17
  • 196
  • 297
  • @rene: Overlooked that part :) Not sure if he can do anything about it, but just to let the old data bubble out... – leppie Mar 01 '11 at 09:39
  • I am not relying on any specific data, but I want to make sure if this data is going to be deserialized in other namespaces, it will do so without any mapping of the mentioned kind. – Yasser Sobhdel Mar 01 '11 at 09:45