C# binary serialization fail

135 Views Asked by At

I used the following codes to serialize an object of a custom class (which also has some members that are also custom classes):

    MyType engine = new MyType(...);
    using (FileStream fs = new FileStream(filename, FileMode.Create))
{
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(fs, engine);
}

After running the code, I am getting a file which doesnt seem to have the right contents to capture the object:

          :Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

Also, when I deserialized the object, i am getting an error:

End of Stream encountered before parsing was completed.

After I added to all related custom classes the attribute [Serializable]. The output file looks more like correct now in that it has detailed data of the object in the file. But then I am getting another different error when I deserialized:

Unable to find assembly 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

Any advice a appreciated.

1

There are 1 best solutions below

0
On

This seems to work:

[Serializable]
public class MyType {
    public int a;
    public int b;
}
using System.Runtime.Serialization.Formatters.Binary;

internal class Program
{
    private static void Main(string[] args)
    {
        MyType engine = new MyType();
        engine.a = 2;
        engine.b = 4;
        File.Delete("d:\\temp\\test.bin");
        FileStream fs = new FileStream("d:\\temp\\test.bin", FileMode.CreateNew);
        //Format the object as Binary
        BinaryFormatter formatter = new BinaryFormatter();
        //It serialize the employee object
#pragma warning disable SYSLIB0011
        formatter.Serialize(fs, engine);
#pragma warning restore SYSLIB0011
        fs.Flush();
        fs.Close();

        fs = new FileStream("d:\\temp\\test.bin", FileMode.Open);

#pragma warning disable SYSLIB0011
        MyType engine2 = (MyType)formatter.Deserialize(fs);
#pragma warning restore SYSLIB0011
        System.Console.WriteLine();
        System.Console.WriteLine($"engine2.a = {engine2.a}");
        System.Console.WriteLine($"engine2.b = {engine2.b}");
    }
}

output:

engine2.a = 2
engine2.b = 4