XmlWriterSettings.Encoding Property

Definition

Gets or sets the type of text encoding to use.

C#
public System.Text.Encoding Encoding { get; set; }

Property Value

The text encoding to use. The default is Encoding.UTF8.

Examples

The following example shows how to set the Encoding property:

C#
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.Encoding = Encoding.Unicode;
XmlWriter writer = XmlWriter.Create("books.xml", settings);

Remarks

The XmlWriter encodes a buffer of characters all at once, rather than character by character. An exception is thrown when the Flush method is called if any encoding errors are encountered.

The Encoding property only applies to the XmlWriter instances that are created either with the specified Stream or with the specified file name. If the XmlWriter instance is created with the specified TextWriter, the Encoding property is overridden by the encoding of the underlying TextWriter. For example, if this property is set to Unicode (UTF-16) for a particular XmlWriter, but the underlying writer is a StreamWriter (which derives from TextWriter) with its encoding set to UTF8, the output will be UTF-8 encoded.

If the XmlWriter instance is created with other output parameters, the Encoding property is ignored.

In the following example:

C#
using (StreamWriter output =
    new StreamWriter(new FileStream("Xml01.xml", FileMode.Create), Encoding.Unicode))
{
    using (XmlWriter xmlWriter =
        XmlWriter.Create(output, new XmlWriterSettings()))
    {
        xmlWriter.WriteStartDocument();
        xmlWriter.WriteStartElement("Root");
        xmlWriter.WriteEndElement();
        xmlWriter.WriteEndDocument();
    }
}

Important

Do not accept an Encoding object from an untrusted source.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0