0

I am trying to get the BinaryLibrary value stored in a binary serialization (BinaryFormatter). I've been following outline from here.

I tried a naive:

    FileStream fs = new FileStream("binary.dat", FileMode.Open);
    try
    {
        BinaryFormatter formatter = new BinaryFormatter();
        object obj = formatter.Deserialize(fs);
    }
    catch (SerializationException e)
    {
        Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
        throw;
    }
    finally
    {
        fs.Close();
    }

Using the debugger I cannot find anything under obj or formatter. Where is the BinaryLibrary value stored ? How can I access it ?

malat
  • 12,152
  • 13
  • 89
  • 158
  • `BinaryFormatter` is not backwards compatible, updating to a newer framework can break deserialization. Because of this, safety and performance issues, I would not recommend using binaryFormatter unless you absolutely have to. But you should either get an actual object that you can inspect in the debugger, or an exception. – JonasH Sep 20 '22 at 14:27
  • 1
    Are you sure the data is serialized by BinaryFormatter? I think you should use [`BinaryReader`](https://learn.microsoft.com/en-us/dotnet/api/system.io.binaryreader?view=net-6.0) to read the data. – shingo Sep 20 '22 at 15:24

1 Answers1

0

The API allows one to register a binder:

So simply register it:

var formatter = new BinaryFormatter();
formatter.Binder = new MyDeserializationBinder();
var obj = formatter.Deserialize(ms);

where definition is:

sealed public class MyDeserializationBinder: SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        Type typeToDeserialize = Type.GetType(String.Format("{0}, {1}",
            typeName, assemblyName));

        Console.WriteLine(String.Format("Input is {0}, {1}", typeName, assemblyName));
        Console.WriteLine(String.Format("Output is {0}", typeToDeserialize.AssemblyQualifiedName));

        return typeToDeserialize;
    }
}

Typical outputs:

Input is System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Output is System.Drawing.Point, System.Drawing.Primitives, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

or:

Input is System.Collections.Generic.List`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934
e089
Output is System.Collections.Generic.List`1[[System.String, System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral
, PublicKeyToken=7cec85d7bea7798e
malat
  • 12,152
  • 13
  • 89
  • 158