Vor einer ganzen Weile habe ich mal die StringWriter-Klasse empfohlen.
Die StringWriter-Klasse nutzt intern UTF-16, wodurch zum Beispiel bei der Xml-Serialisierung von Klassen auch das Ergebnis in UTF-16 vorliegt. Dies ist nicht zwangsläufig gewünscht, bei mir hat dadurch ein Backend-Service gestreikt.
Um trotzdem den StringWriter weiter zu verwenden, muss man sich eine eigene Klasse schreiben, welche von der StringWriter ableitet und das Encoding-Property überschreibt:
using System;
using System.IO;
using System.Text;
namespace Utilities.IO
{
/// <summary>
/// A simple class derived from StringWriter, but which allows
/// the user to select which Encoding is used. This is most
/// likely to be used with XmlTextWriter, which uses the Encoding
/// property to determine which encoding to specify in the XML.
/// </summary>
public class StringWriterWithEncoding : StringWriter
{
private Encoding _encoding;
/// <summary>
/// Initializes a new instance of the StringWriterWithEncoding class
/// with the specified encoding.
/// </summary>
/// <param name = "encoding">The encoding to report.</param>
public StringWriterWithEncoding(Encoding encoding)
: base()
{
this._encoding = encoding;
}
/// <summary>
/// Initializes a new instance of the StringWriter class with the
/// specified format control and encoding.
/// </summary>
/// <param name = "encoding">The encoding to report.</param>
/// <param name = "formatProvider">An IFormatProvider object that controls formatting.</param>
public StringWriterWithEncoding(Encoding encoding, IFormatProvider formatProvider)
: base(formatProvider)
{
this._encoding = encoding;
}
/// <summary>
/// Initializes a new instance of the StringWriter class that writes to the
/// specified StringBuilder, and reports the specified encoding.
/// </summary>
/// <param name = "encoding">The encoding to report.</param>
/// <param name = "sb">The StringBuilder to write to. </param>
public StringWriterWithEncoding(Encoding encoding, StringBuilder sb)
: base(sb)
{
this._encoding = encoding;
}
/// <summary>
/// Initializes a new instance of the StringWriter class that writes to the specified
/// StringBuilder, has the specified format provider, and reports the specified encoding.
/// </summary>
/// <param name = "encoding">The encoding to report.</param>
/// <param name = "sb">The StringBuilder to write to. </param>
/// <param name = "formatProvider">An IFormatProvider object that controls formatting.</param>
public StringWriterWithEncoding(Encoding encoding, StringBuilder sb, IFormatProvider formatProvider)
: base(sb, formatProvider)
{
this._encoding = encoding;
}
/// <summary>
/// Gets the Encoding in which the output is written.
/// </summary>
public override Encoding Encoding
{
get { return this._encoding; }
}
}
}
Update:
Habe die Klasse mal um Kommentare erweitert.