0

I have the following code to serialize /deserialize a DataTable:

    public static byte[] Serialize(DataTable dt)
    {
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        formatter.Serialize(stream, dt); 
        return stream.GetBuffer(); 
    }


    public static DataTable Deserialize(byte[] buffer) 
    {
        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
        System.Runtime.Serialization.IFormatter formatter = new BinaryFormatter();

        return formatter.Deserialize(stream) as DataTable; 
    }  

The serialize method works fine but the deserialize method produces this error:

  The input stream is not a valid binary format. The starting contents (in bytes) are: 1F-8B-08 ...

I am 99% sure I have gotten this method to work in the past, not sure whats wrong.

Sean Thoman
  • 7,429
  • 6
  • 56
  • 103
  • 5
    Are you sure you are giving the exact output of `Serialize` to `Deserialize`? try running `Deserialize(Serialize(object))` and see if it errors. – Daniel Aug 12 '11 at 20:27

1 Answers1

2

you should not use GetBuffer() but ToArray() since the latter returns really the content while Getbuffer() could return uninitialized bytes...

see
http://msdn.microsoft.com/en-us/library/system.io.memorystream.toarray.aspx
http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx

Yahia
  • 69,653
  • 9
  • 115
  • 144