从MemoryStream问题反序列化

时间:2013-04-12 12:52:46

标签: c# .net deserialization memorystream

我需要帮助来弄清楚如何从MemoryStream反序列化。

var xmlStream = new MemoryStream();
e.Extract(xmlStream);

if (xmlStream != null)
{
    TextReader tr = new StreamReader(xmlStream);
    var contentItems = new ContentItems();
    var serializer = new XmlSerializer(typeof(ContentItems));
    contentItems = (ContentItems)serializer.Deserialize(tr); // Error is here

1 个答案:

答案 0 :(得分:3)

我找到了解决方案

我们应该添加

 xmlStream.Seek(0, SeekOrigin.Begin);

所以最终的代码看起来像是

var xmlStream = new MemoryStream();
e.Extract(xmlStream);

if (xmlStream != null)
{
    xmlStream.Seek(0, SeekOrigin.Begin);
    var contentItems = new ContentItems();
    var serializer = new XmlSerializer(typeof(ContentItems));
    contentItems = (ContentItems)serializer.Deserialize(xmlStream); // NO ERROR