0

In application called "application1" I serialize this structure into binary:

namespace namespace1
{ 
[System.Serializeable]
class ClassA
   { 
     List<ClassB> List 
   } 
}

In application called "application2" I have to deserialize this binary but my ClassA and ClassB have to be inside namespace2 instead of namespace1.

So I wrote a serialization binder:

public class TypeNameConverter : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            assemblyName = Assembly.GetExecutingAssembly().FullName;

            if (typeName.Contains("nemespace1."))
                typeName = typeName.Replace("nemespace1.", "nemespace2.");

            Type retType = Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
            return retType;
        }
    }

and I use it like this:

 binaryFormatter.Binder = new TypeNameConverter();
 (T)binaryFormatter.Deserialize(memoryStream);

And this sucessfully deserializes namespace1.ClassA into namespace2.ClassA, but fails to further deserialize list od nemespace1.ClassB into list of namespace2.ClassB. I guess it fails because list of ClassB is encapsulated into ClassA and BindToType() function does not get called for the "inner elements", it gets called only once for ClassA, then trys to deserialize ClassA and fails to extract list of ClassB with error:

 SerializationException: Could not find type
    'System.Collections.Generic.List`1[[namespace1.ClassB, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]'.

I cannot do any adjustments to application1 (cannot change the way I do serialization) I can only adjust deserialization logic in application2.

I am trying to find the solution for this particular problem, anyone had similar problem or maybe an idea on how to solve this?

Thanks!

Joakim
  • 31
  • 3
  • 1
    Have you considered serialising into a non-binary format (like JSON)? – mjwills Jul 10 '18 at 13:43
  • The thing is, I cannot do any adjustments to "application1" where i do serialization. I must find the way to deserialize this data without changing the serialization method. Thanks for your comment. – Joakim Jul 10 '18 at 13:47

1 Answers1

1

The only solution to the problem in question I found is manually changing the type inside already serialized binary file. That includes reading binary file which contains serialized objects of type namespace1.ClassA, finding the bytes in binary file which represent the string which defines the type (that is "namespace1.ClassA") and replacing those bytes with string "namespace2.ClassA", thus making deserializer think that serialized object is of type namespace2.ClassA instead of namespace1.ClassA, and this works!

The link to s.o. question containing golden information, everything you need to know to do this, and an example code. How to analyse contents of binary serialization stream?

Joakim
  • 31
  • 3