Reputation: 14071
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.
}
Upvotes: 0
Views: 99
Reputation: 14071
The reason for the exception Missing XML declaration with an encoding
is the missing XML line
<?xml version="1.0" encoding="utf-8"?>
As discussed above, there are 2 solutions:
XmlWriter
creates the line automatically: using (XmlWriter writer = XmlWriter.Create(fn, settings))
XmlTextWriter
and add writer.WriteStartDocument();
Kudos to all who helped above in the discussion.
Upvotes: 1