反序列化不工作的MemoryStream [英] Deserialization not working on MemoryStream

查看:184
本文介绍了反序列化不工作的MemoryStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//Serialize the Object
MemoryStream ms = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms , ObjectToSerialize);
byte[] arrbyte = new byte[ms .Length];
ms.Read(arrbyte , 0, (int)ms .Length);
ms.Close();

//Deserialize the Object
Stream s = new MemoryStream(arrbyte);
s.Position = 0;
Object obj = formatter.Deserialize(s);//Throws an Exception
s.Close();

如果我尝试用上述方式来反序列化给人的异常为

If I try to Deserialize with the above way it gives the Exception as

二进制流0不包含一个有效的BinaryHeader。可能的原因是序列化和反序列化的无效流或对象版本更改。

'Binary stream '0' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.'

在哪里下面的代码工作。

Where below code is working

//Serialize the Object
IFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, ObjectToSerialize);
ms.Seek(0, SeekOrigin.Begin);
byte[] arrbyte = ms.ToArray();

//Deserialize the Object
Stream s= new MemoryStream(byt);
stream1.Position = 0;
Object obj = formatter.Deserialize(s);
stream1.Close();



唯一的区别是在第一种方法使用Read方法,其中作为第二个填充字节数组使用寻求和放大器; ToArray的()来填充字节数组。
什么是异常的原因。

The only difference is the first approach uses the Read method to populate the byte array where as the second one uses the Seek & ToArray() to populate the byte array. What is the reason for the Exception.

推荐答案

第一种方式序列化对象这会导致将MemoryStream的MemoryStream定位在写入的字节的末尾。从那里,你读到结尾的所有字节到字节数组:无(因为MemoryStream的已经是结尾)

The first way serializes the object to the MemoryStream which results in the MemoryStream being positioned at the end of the bytes written. From there you read all bytes to the end into the byte array: none (because the MemoryStream is already at the end).

您可以将MemoryStream内移动的位置从中读取之前启动:

You can move the position within the MemoryStream to the start before reading from it:

ms.Seek(0, SeekOrigin.Begin);



但随后的代码不完全一样的第二种方法:创建毫秒的一个新的字节数组。长度长,并从流的字节数组复制所有字节。那么,为什么另起炉灶?

But the code then does exactly the same as the second way: create a new byte array of ms.Length length, and copy all bytes from the stream to the byte array. So why reinvent the wheel?

请注意,第二个方法不需要寻求为ToArray的总是副本的所有字节,独立的MemoryStream的位置。

Note that the second way doesn't require the Seek as ToArray always copies all bytes, independent of the position of the MemoryStream.

这篇关于反序列化不工作的MemoryStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆