Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top