How to use XmlWriter along with StringWriter to properly serialize a UTF-8 string
Today, I (re)learned how to serialize an XML to a UTF-8 string. Like all the other times I did this, I got backstabbed by StringWriter, which only supports UTF-16. A simple code snippet like this: await using var sw = new StringWriter(); await using var w = XmlWriter.Create(sw, new() { Async = true }); ... await w.FlushAsync(); return sw.ToString(); Will emit this output: <?xml version="1.0" encoding="utf-16"?><... There’s nothing inherently wrong with UTF-16, but XML is usually UTF-8, so one must do something about it. StringWriter exposes an Encoding property, but it is read-only for unknown reasons. One might think that given that the XmlWriter allows setting its own Encoding value, something like this would work: ...