Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

TextWriter and StringWriter

Reference for TextWriter in C#: StringWriter, StreamWriter, TextWriter.Null, Synchronized, IndentedTextWriter, custom writers, NewLine and async writes.

TextWriter is the abstract base class for everything in .NET that writes characters: Console.Out, StreamWriter (to a file or stream), StringWriter (to a string) and HttpResponse writers all derive from it. It supplies the familiar Write, WriteLine and WriteAsync overloads for all primitive types, formatted strings, and ISpanFormattable values, so code that takes a TextWriter parameter works with any destination.

StringWriter is the in-memory implementation: it collects text in a StringBuilder and gives it back with ToString(). It is the standard tool for capturing output in tests, building text with code that expects a writer (templating, serializers, Console.SetOut), and writing helper methods that can target a file in production and a string in tests.

C#
using var writer = new StringWriter();
writer.WriteLine("Hello");
writer.Write(42);
string text = writer.ToString();

Try it

C# One method, many destinations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# NewLine, indentation and a custom writer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public abstract class TextWriter : MarshalByRefObject, IDisposable, IAsyncDisposable
{
    public abstract Encoding Encoding { get; }
    public virtual string NewLine { get; set; }
    public virtual IFormatProvider FormatProvider { get; }

    public virtual void Write(char value);
    public virtual void Write(string? value);
    public virtual void WriteLine(string? value);
    public virtual Task WriteLineAsync(string? value);
    public virtual void Flush();

    public static readonly TextWriter Null;
    public static TextWriter Synchronized(TextWriter writer);
}

public class StringWriter : TextWriter
{
    public StringWriter();
    public StringWriter(IFormatProvider? formatProvider);
    public StringWriter(StringBuilder sb);
    public virtual StringBuilder GetStringBuilder();
    public override string ToString();
}
Member Description
Encoding The encoding the writer uses (UTF-16 for StringWriter). Required when you subclass.
NewLine The string WriteLine appends. Defaults to Environment.NewLine; set it to "\n" for portable output.
FormatProvider Culture used when formatting numbers and dates. null means the current culture.
Write / WriteLine Overloads for every primitive, string, char[], object, composite formats and interpolated strings.
Flush / FlushAsync Pushes buffered data to the destination.
Null A writer that discards everything.
Synchronized(writer) Wraps a writer so concurrent calls are serialized.
GetStringBuilder() The StringBuilder behind a StringWriter; you can inspect or clear it.

Returns: StringWriter.ToString() returns everything written so far. It stays valid after the writer is disposed.

Errors: ObjectDisposedException when writing to a disposed writer, IOException for failures of the underlying stream.

Usage notes

  • Accept TextWriter, not a concrete type. A method such as Render(TextWriter output) serves the console, files, HTTP responses and tests alike.
  • Subclassing is cheap. Overriding Encoding and Write(char) is enough; every other Write overload funnels into it. Override Write(string) and Write(char[], int, int) too if performance matters.
  • Dispose file writers. StreamWriter buffers its output. Without Dispose() or Flush(), the last bytes may never reach the file. StringWriter holds no resources, but disposing it is harmless and keeps analyzers quiet.
  • Culture. The StringWriter(IFormatProvider) constructor sets FormatProvider, which decides decimal separators. Pass CultureInfo.InvariantCulture when the text is parsed by a machine later.
  • Thread safety. A plain TextWriter is not thread-safe. TextWriter.Synchronized(writer) makes single calls atomic, but two consecutive WriteLine calls from different threads can still interleave their lines.
  • Newline portability. WriteLine on Windows writes \r\n by default. Set NewLine before writing if the output must be identical across systems, for example in golden-file tests.
  • Capturing the console. Console.SetOut(new StringWriter()) redirects all Console.WriteLine calls; restore the original writer afterwards.
  • Reading counterparts. TextReader, StringReader and StreamReader mirror these classes on the input side.