将byte []反序列化为DataTable

时间:2011-08-12 20:24:45

标签: c# serialization datatable binary-serialization

我有以下代码来序列化/反序列化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方法工作正常,但deserialize方法会产生此错误:

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

我99%肯定我已经让这种方法在过去工作,不知道什么是错的。

1 个答案:

答案 0 :(得分: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