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.
}
What if you use
XmlWriter.Create()
instead of the deprecatedXmlTextWriter
?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"?>
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)
XmlTextWriter
was introduced in .NET 1. In .NET 2 (circa 2005) it was superseded byXmlWriter.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 toCreate(...)
.But because
XmlTextWriter
was widely used in .NET 1 they couldn’t just remove it, so it has persisted. For quite a long time.Show 2 more comments