0

我有以下代码来序列化/反序列化 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; 
    }  

serialize 方法工作正常,但反序列化方法会产生此错误:

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

我有 99% 的把握在过去使用过这种方法,但不知道出了什么问题。

4

1 回答 1

2

你不应该使用GetBuffer(),但ToArray()因为后者返回真正的内容,而Getbuffer()可能返回未初始化的字节......

请参阅
http://msdn.microsoft.com/en-us/library/system.io.memorystream.toarray.aspx
http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer。 aspx

于 2011-08-12T20:30:38.950 回答