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.
}
The reason for the exception
Missing XML declaration with an encodingis the missing XML lineAs discussed above, there are 2 solutions:
XmlWritercreates the line automatically:using (XmlWriter writer = XmlWriter.Create(fn, settings))XmlTextWriterand addwriter.WriteStartDocument();Kudos to all who helped above in the discussion.