无法使用 XmlWriter 编码为 UTF8

Unable to encode to UTF8 with XmlWriter

我正在 WCF 中开发 Web 服务。

我想 return 一个 xml 文件,UTF8。

我的代码是:

StringBuilder output = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 };
using (XmlWriter writer = XmlWriter.Create(output, settings))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("Response", Resources.nameSpaceUri);
    /* Some functions */
    writer.WriteEndElement();
    writer.WriteEndDocument();
}
return output.ToString();

但结果是这样的:

<?xml version="1.0" encoding="utf-16"?>
<Response xmlns="http://namespace">
    <!-- Content -->
</Response>

为什么我的回复是 UTF-16?

这仅仅是因为 StringBuilder(和 String、Char、char)使用 UTF-16。作者适当地声明了编码。如果您使用以文件或流为目标的编写器,那么它会使用设置中的编码。