如何在使用二进制DataContactSerializer进行序列化后反序列化?

时间:2015-06-11 23:56:03

标签: c# .net serialization

使用默认 DataContractSerializer序列化后,我成功反序列化了。

MemoryStream ms = new MemoryStream();
DataContractSerializer dcSerializer = new DataContractSerializer( typeof( Library ) );
dcSerializer.WriteObject( ms, lib );
ms.Position = 0;
var returned = dcSerializer.ReadObject( ms ) as Library;

但如果我使用二进制编写器和二进制阅读器,则此代码会抛出异常。

MemoryStream ms2 = new MemoryStream();
var binWriter = XmlDictionaryWriter.CreateBinaryWriter( ms2 );
dcSerializer.WriteObject( binWriter, lib );
ms2.Position = 0;
var binReader = XmlDictionaryReader.CreateBinaryReader( ms2, XmlDictionaryReaderQuotas.Max );
// throws an exception
var returned2 = dcSerializer.ReadObject( binReader ) as Library; 

异常消息是

There was an error deserializing the object of type Test.Library.
Unexpected end of file.
Following elements are not closed: Pages, Book, Books, Library.

这是图书馆课程。

[Serializable]
public class Library
{
    [XmlAttribute, DataMember]
    public string Name;
    [DataMember]
    public Person Owner;
    [XmlAttribute, DataMember]
    public DateTime DateEstablished;
    [DataMember]
    public List<Book> Books;
}

和Book课程。

[Serializable]
public class Book
{
    [XmlAttribute, DataMember]
    public string Title, ISBN, Author;
    [XmlAttribute, DataMember]
    public DateTime DatePublished;
    [XmlAttribute, DataMember]
    public int Pages;
    [DataMember]
    public List<string> TableOfContents;
}

我在.net小提琴上设置了一个示例。 https://dotnetfiddle.net/wV8VAh

它不会在网站上运行,因为它缺少System.Runtime.Serialization程序集。但是,如果将其放入Visual Studio项目并添加程序集,它将运行得很好。 (并抛出异常!)

我错过了什么? 谢谢!

1 个答案:

答案 0 :(得分:0)

您可能需要在执行WriteObject后刷新writer和stream:

binWriter.Flush()