Deserialization not working on MemoryStream

霸气de小男生 提交于 2019-12-21 08:26:21

问题


//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. 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. What is the reason for the Exception.


回答1:


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).

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?

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




回答2:


You should seek to the beginning of the stream in the first case, before reading the content of the stream, while in the second case seeking is not needed before the ToArray call.



来源:https://stackoverflow.com/questions/2228850/deserialization-not-working-on-memorystream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!