DataContractSerializer reading causes “Missing XML declaration with an encoding”, any idea why?

I write a record to a XML file with an DataContractSerializer. Works with no issues. But when reading back I am getting an exception: Loading snapshot failed, An XML declaration with an encoding is required for all non-UTF8 documents.

Any idea? Or better, can I configure the XmlTextWriter to write that encoding information?

Writing:

DataContractSerializer serializer = new(typeof(RMonitorSnapshot));
using (XmlTextWriter writer = new(fn, Encoding.Unicode))
{
    writer.Formatting = Formatting.Indented; // indent the Xml so it’s human readable
    serializer.WriteObject(writer, snapshot);
    writer.Flush();
}

Reading:

RMonitorSnapshot? snapshot = null;
DataContractSerializer serializer = new(typeof(RMonitorSnapshot));

try {
    using (FileStream fs = File.Open(fn, FileMode.Open)) {
        snapshot = serializer.ReadObject(fs) as RMonitorSnapshot;
    }
}
catch (Exception ex) {
...  Loading snapshot failed, An XML declaration with an encoding is required for all non-UTF8 documents. 
}

  • 1

    What if you use XmlWriter.Create() instead of the deprecated XmlTextWriter?

    – 

  • This seems to resolve the issue. If you like, you can post it as answer. Unlike XmlTextWriter it adds <?xml version="1.0" encoding="utf-8"?>

    – 




  • 1

    This behavior is due to the fact that XmlTextWriter should have backward compatibility where writing a header requires explicitly calling the WriteStartDocument method, while DataContractSerializer does not explicitly call this method because it depends on data that is not available to it (this is the Encoding parameter)

    – 

  • 1

    XmlTextWriter was introduced in .NET 1. In .NET 2 (circa 2005) it was superseded by XmlWriter.Create() as stated in the docs: Starting with the .NET Framework 2.0, we recommend that you create XmlWriter instances by using the XmlWriter.Create method and the XmlWriterSettings class to take advantage of new functionality. This all happened long ago, but I think MSFT made the change so they could manufacture different concrete writers depending on the settings passed in to Create(...).

    – 




  • 1

    But because XmlTextWriter was widely used in .NET 1 they couldn’t just remove it, so it has persisted. For quite a long time.

    – 

Leave a Comment