开发者

Deserializing a byte[] back into a DataTable

开发者 https://www.devze.com 2023-03-28 07:09 出处:网络
I have the following code to serialize /deserialize a DataTable: public static byte[] Serialize(DataTable dt)

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.Serializa开发者_运维问答tion.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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号