简体   繁体   English

反序列化不适用于MemoryStream

[英]Deserialization not working on 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 如果我尝试使用上面的方式反序列化,它会将异常作为

'Binary stream '0' does not contain a valid BinaryHeader. '二进制流'0'不包含有效的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();

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. 唯一的区别是第一种方法使用Read方法填充字节数组,而第二种方法使用Seek&ToArray()来填充字节数组。 What is the reason for the Exception. 异常的原因是什么。

The first way serializes the object to the MemoryStream which results in the MemoryStream being positioned at the end of the bytes written. 第一种方法将对象序列化为MemoryStream,这导致MemoryStream位于写入字节的末尾。 From there you read all bytes to the end into the byte array: none (because the MemoryStream is already at the end). 从那里你将所有字节读到字节数组的末尾:none(因为MemoryStream已经在最后)。

You can move the position within the MemoryStream to the start before reading from it: 您可以在读取之前将MemoryStream中的位置移动到开头:

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. 但是代码与第二种方式完全相同:创建一个ms.Length长度的新字节数组,并将所有字节从流复制到字节数组。 So why reinvent the wheel? 为什么要重新发明轮子呢?

Note that the second way doesn't require the Seek as ToArray always copies all bytes, independent of the position of the MemoryStream. 请注意,第二种方式不需要Seek,因为ToArray始终复制所有字节,与MemoryStream的位置无关。

在读取流的内容之前,您应该在第一种情况下寻找流的开头,而在第二种情况下,在ToArray调用之前不需要寻求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM