【问题标题】:Deserializing a byte[] back into a DataTable将 byte[] 反序列化回 DataTable
【发布时间】:2011-08-12 20:24:44
【问题描述】:

我有以下代码来序列化/反序列化数据表:

    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 input stream is not a valid binary format. The starting contents (in bytes) are: 1F-8B-08 ...

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

【问题讨论】:

  • 您确定将Serialize 的准确输出提供给Deserialize?尝试运行Deserialize(Serialize(object)) 看看是否出错。

标签: c# serialization datatable binary-serialization


【解决方案1】:

你不应该使用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

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多