Search code examples
c#serializationmemory-mapped-filesbinaryformatter

How to deserialize BinaryFormatter


I'm trying to serialize my MMF to file and here is the code:

class MMF {
    private const string filename = @"c:\NFS";
    private long offset = 0;
    private long length = 194;
    private byte[] buffer;
    public MMF() {
        using (var mmf =
            MemoryMappedFile.CreateFromFile(filename, FileMode.OpenOrCreate, null, offset + length, MemoryMappedFileAccess.ReadWriteExecute)) {
            using (var accessor = mmf.CreateViewAccessor(offset, length, MemoryMappedFileAccess.ReadWriteExecute)) {
                buffer = new byte[194];
                /*FS fs = new FS();
                fs.Files[0].Path = "test";
                accessor.WriteArray<byte>(0, buffer, 0, (int)length);*/
                accessor.ReadArray<byte>(0, buffer, 0, (int)length);
                FS fs = (FS)ToObject(buffer);
                Console.WriteLine(fs.Files[0].Path);
                }
            }
        }
    private byte[] ToByteArray(object source) {
        var formatter = new BinaryFormatter();
        using (var stream = new MemoryStream()) {
            formatter.Serialize(stream, source);
            return stream.ToArray();
            }
        }
    private object ToObject(byte[] source) {
        var formatter = new BinaryFormatter();
        using (var stream = new MemoryStream(source)) {
            formatter.Deserialize(stream);
            return stream;
            }
        }
    }

On deserialization part I'm getting error:

An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll

Additional information: A binary stream "0" does not contain a valid binary header BinaryHeader. Possible causes: invalid stream or object version change between serialization and deserialization.

How to Deserialize the file properly? Where is my mistake?

thank you


Solution

  • You might want to let MMF implement ISerializable and implement the GetObjectData method.