Reputation: 129
I am trying to save xml string as file, file is getting saved in UTF16 format. What might be the issue?
private void SaveFile(string xmlData, string fileName)
{
File.WriteAllText(fileName, xmlData, Encoding.UTF8);
}
Even though I have mentioned Encoding as UTF8 still the file is getting saved in UTF16 format.
Upvotes: 1
Views: 982
Reputation: 1063774
I'm guessing you have done something like:
string xml;
using(var sw = new StringWriter()) {
xmlSerializer.Serialize(sw, obj);
xml = sw.ToString();
}
in which case yes, the xml will internally declare utf-16, because it has correctly determined that it is writing to something that is inherently utf-16. There are probably ways to work around this in the writer (XmlWriterSettings.Encoding
, for example), but a better approach would be either:
StreamWriter
onto the fileMemoryStream
rather than a StringWriter
, since MemoryStream
has no inherent utf-16 encodingThe encoding of a file is not quite the same thing as the declared encoding in the xml; if the xml as a string says utf-16, that won't magically change just because you write the string as utf-8
Upvotes: 2