user3651810
user3651810

Reputation: 129

File is getting saved in UTF16 format. What might be the issue?

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

Answers (1)

Marc Gravell
Marc Gravell

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:

  • to write/serialize directly to the file, for example via a StreamWriter onto the file
  • to write/serialize to a MemoryStream rather than a StringWriter, since MemoryStream has no inherent utf-16 encoding

The 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

Related Questions