将 byte[] 反序列化回 DataTable

发布于 2024-11-29 06:00:45 字数 889 浏览 2 评论 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; 
    }  

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

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

我 99% 确定我过去已经使用过此方法,但不确定出了什么问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

开始看清了 2024-12-06 06:00:45

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文