> ## Content Index
> Fetch the complete content index at: https://blog.jsinh.in/llms.txt
> Use this file to discover other available public pages before exploring further.

# Use UTF-8 encoding for StringWriter in C#
- URL: https://blog.jsinh.in/use-utf-8-encoding-for-stringwriter-in-c/
- Published: 2013-06-12T10:00:39.000Z
- Updated: 2026-07-07T15:15:28.000Z
- Author: Jsinh
- Tags: #Import 2026-10-04 19:16

All .NET string is in Unicode (UTF-16) encoding format.

So when you are using StringWriter to create your XML it will use UTF-16 encoding.

Example when creating XML :

```
var serializer = new XmlSerializer(yourModel.GetType(), string.Empty);
var stringBuilder = new StringBuilder();
using (var stringWriter = new StringWriter())
{
      serializer.Serialize(stringWriter, yourModel);
      stringBuilder.Append(stringWriter);
}

var resultString = stringBuilder.ToString();

```

But you want your XML to use UTF-8 encoding. One good way of doing this is to derive the StringWriter class and override the encoding.

```
	using System.IO;
    using System.Text;

    public sealed class ExtentedStringWriter : StringWriter
    {
        private readonly Encoding stringWriterEncoding;
        public ExtentedStringWriter(StringBuilder builder, Encoding desiredEncoding)
            : base(builder)
        {
            this.stringWriterEncoding = desiredEncoding;
        }

        public override Encoding Encoding
        {
            get
            {
                return this.stringWriterEncoding;
            }
        }
    }

```

Then you can use `ExtendedStringWriter` instead of `StringWriter` in the above example.