Search code examples
c#serializationdebuggingmode

Deserialization in debug mode?


Can anyone explain why the following is happening:

When we serialize a file in debug mode, we can open it again in debug mode, but not at runtime. When we serialize a file in runtime mode, we can open it again in runtime mode, but not at debug mode.

Now I know you're gonna say: thats because they have different assemblies. But we use a custom Binder, as specified below ... Furthermore, if we compare both types, "bool same = (o.GetType() == c.GetType())", we get always "true" as result ???

Then why can't we open the file ??

public class Binder : SerializationBinder {

    public override Type BindToType(string assemblyName, string typeName) {
        Type tyType = null;
        string sShortAssemblyName = assemblyName.Split(',')[0];
        Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
        if (sShortAssemblyName.ToLower() == "debugName")
        {
            sShortAssemblyName = "runtimeName";
        }
        foreach (Assembly ayAssembly in ayAssemblies) {
            if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0]) {
                tyType = ayAssembly.GetType(typeName);
                break;
            }
        }
        return tyType;
    }
}



    public static DocumentClass Read(string fullFilePath, bool useSimpleFormat)
    {
        DocumentClass c = new DocumentClass();
        c.CreatedFromReadFile = true;

        Stream s = File.OpenRead(fullFilePath);// f.Open(FileMode.Open);
        BinaryFormatter b = new BinaryFormatter();
        if (useSimpleFormat)
        {
            b.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
        }
        b.Binder = new Binder();

        try
        {
            object o = b.Deserialize(s);
            c = (DocumentClass)o;
            c.CreatedFromReadFile = true;

           string objOriginal = o.GetType().AssemblyQualifiedName + "_" + o.GetType().FullName;
            string objTarget = c.GetType().AssemblyQualifiedName + "_" + c.GetType().FullName;
            bool same = (o.GetType() == c.GetType());

            if (c.DocumentTypeID <= 0)
            {
                throw new Exception("Invalid file format");
            }
        }
        catch( Exception exc )
        {
            s.Close();
            if (!useSimpleFormat)
            {
                return Read(fullFilePath, true);
            }
            throw exc;

        }
        finally
        {
            s.Close();
        }
        return c;
    }

Solution

  • oh no ... i'm an idiot ...

    some of the fields of the class are obfuscated in runtime mode ...

    • hits head to table *

    sorry people ... thanks for all the help ...