将 byte[] 反序列化回 DataTable
我有以下代码来序列化/反序列化 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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
you should not use
GetBuffer()
butToArray()
since the latter returns really the content whileGetbuffer()
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