Horst Walter
Horst Walter

Reputation: 14071

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. 
}

Upvotes: 0

Views: 99

Answers (1)

Horst Walter
Horst Walter

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:

  1. Using XmlWriter creates the line automatically: using (XmlWriter writer = XmlWriter.Create(fn, settings))
  2. Using XmlTextWriter and add writer.WriteStartDocument();

Kudos to all who helped above in the discussion.

Upvotes: 1

Related Questions