C# TextWriter
last modified November 6, 2026
In this article we show how to use the TextWriter class in C#.
TextWriter from the System.IO namespace is the
abstract base class for writers of characters. Its main subclasses are
StreamWriter, which encodes text into a stream, and
StringWriter, which writes into a StringBuilder.
Console.Out and Console.Error are
TextWriter instances as well.
The class defines the Write and WriteLine
overloads, their asynchronous versions, Flush, and the
Encoding, FormatProvider, and NewLine
properties. Taking a TextWriter parameter lets one method write to
any of these targets.
One method, many targets
The first example writes a summary of temperatures to the console, a file, and a string.
int[] temps = [21, 23, 19, 25, 22];
Summary(Console.Out, temps);
using (var file = File.CreateText("summary.txt"))
{
Summary(file, temps);
}
Console.WriteLine($"File: {File.ReadAllText("summary.txt").Length} chars");
using var sw = new StringWriter();
Summary(sw, temps);
Console.WriteLine($"String: {sw.ToString().Length} chars");
File.Delete("summary.txt");
static void Summary(TextWriter writer, int[] values)
{
writer.WriteLine($"count: {values.Length}");
writer.WriteLine($"min: {values.Min()}");
writer.WriteLine($"max: {values.Max()}");
writer.WriteLine("avg: {0:F1}", values.Average());
}
Summary knows only the TextWriter methods.
using (var file = File.CreateText("summary.txt"))
File.CreateText returns a StreamWriter for a new UTF-8
file. The file and the string get the same 41 characters that appear on the
console.
writer.WriteLine("avg: {0:F1}", values.Average());
Composite format strings work with every writer and use its
FormatProvider.
$ dotnet run count: 5 min: 19 max: 25 avg: 22.0 File: 41 chars String: 41 chars
Standard output and standard error
A console program has two output streams. Console.Out is for
results and Console.Error for diagnostics, so that redirecting the
results does not mix them with error messages.
string[] inputs = ["12", "x7", "40", ""];
int sum = 0;
foreach (var input in inputs)
{
if (int.TryParse(input, out int n))
{
sum += n;
}
else
{
Console.Error.WriteLine($"warning: skipping invalid value '{input}'");
}
}
Console.Out.WriteLine(sum);
The program sums the valid numbers and reports invalid ones on standard error.
We redirect standard error to a file with 2>. Only the sum
appears on the terminal; the warnings are in errors.log.
$ dotnet run 2> errors.log 52 $ cat errors.log warning: skipping invalid value 'x7' warning: skipping invalid value ''
A custom TextWriter
A subclass must implement the Encoding property and
Write(char). All other Write overloads end up calling
Write(char), so the writer works, but slowly. Overriding
Write(string) as well avoids a call per character.
using System.Text;
using var log = new StringWriter();
using var tee = new TeeWriter(Console.Out, log);
tee.WriteLine("Starting job");
tee.Write("Progress: ");
tee.WriteLine("{0:P0}", 0.5);
tee.WriteLine('!');
Console.WriteLine($"--- log copy has {log.ToString().Length} chars");
Console.Write(log);
class TeeWriter(TextWriter first, TextWriter second) : TextWriter
{
public override Encoding Encoding => first.Encoding;
public override void Write(char value)
{
first.Write(value);
second.Write(value);
}
public override void Write(string? value)
{
first.Write(value);
second.Write(value);
}
public override void Flush()
{
first.Flush();
second.Flush();
}
}
TeeWriter sends everything to two writers, like the Unix
tee command. We use it to print messages and keep a copy in a
string.
public override void Write(string? value)
WriteLine(string) in the base class writes the string and then
CoreNewLine, so both calls go through our overrides.
tee.WriteLine("{0:P0}", 0.5);
Formatting is done by the base class before our Write methods are
called.
$ dotnet run Starting job Progress: 50% ! --- log copy has 29 chars Starting job Progress: 50% !
Indented output
IndentedTextWriter from the System.CodeDom.Compiler
namespace wraps a writer and adds indentation at the start of each line.
using System.CodeDom.Compiler;
using var sw = new StringWriter();
using var writer = new IndentedTextWriter(sw, " ");
WriteNode(writer, "root", ["src", "docs"], 0);
Console.Write(sw);
static void WriteNode(IndentedTextWriter writer, string name, string[] children, int depth)
{
writer.WriteLine($"{name}/");
writer.Indent++;
foreach (var child in children)
{
if (depth == 0)
{
WriteNode(writer, child, [$"{child}-a.txt", $"{child}-b.txt"], depth + 1);
}
else
{
writer.WriteLine(child);
}
}
writer.Indent--;
}
We print a small directory tree with a recursive method.
using var writer = new IndentedTextWriter(sw, " ");
The second argument is the string used for one level of indentation; the default is four spaces.
writer.Indent++;
Indent is the current level. We increase it before writing the
children and decrease it afterwards, so each nesting level is indented by two
more spaces.
$ dotnet run
root/
src/
src-a.txt
src-b.txt
docs/
docs-a.txt
docs-b.txt
TextWriter.Null
TextWriter.Null is a writer that discards everything. It can
switch off optional output, such as logging, without changing the code that
writes it.
Work(TextWriter.Null);
Console.WriteLine($"Null writer: done, {TextWriter.Null.GetType().Name}");
using var log = new StringWriter();
Work(log);
Console.WriteLine($"String writer: {log.ToString().Split('\n').Length - 1} lines logged");
static void Work(TextWriter log)
{
for (int i = 1; i <= 1000; i++)
{
log.WriteLine($"step {i}");
}
}
Work writes a line for each of its 1000 steps.
With the null writer nothing is stored. Note that the interpolated string is still built for each call; the null writer only drops the result.
$ dotnet run Null writer: done, NullTextWriter String writer: 1000 lines logged
Writing from several threads
Writers are not thread-safe. TextWriter.Synchronized returns a
wrapper that locks around every call.
Console.WriteLine($"Plain writer: {Run(w => w)}");
Console.WriteLine($"Synchronized writer: {Run(TextWriter.Synchronized)}");
static string Run(Func<TextWriter, TextWriter> wrap)
{
using var sw = new StringWriter();
TextWriter writer = wrap(sw);
try
{
Parallel.For(0, 4, t =>
{
for (int i = 0; i < 10_000; i++)
{
writer.WriteLine($"thread {t} line {i}");
}
});
}
catch (AggregateException)
{
return "failed with an exception";
}
int lines = sw.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries).Length;
return $"{lines} lines ({writer.GetType().Name})";
}
Four threads each write 10,000 lines to a StringWriter, once
directly and once through the wrapper.
Without synchronization, the threads corrupt the internal state of the
StringBuilder. The exact result varies between runs; here the
writes ended with an exception. The synchronized writer keeps all 40,000
lines. Console.Out is synchronized in the same way.
$ dotnet run Plain writer: failed with an exception Synchronized writer: 40000 lines (SyncTextWriter)
Source
In this article we have used TextWriter as a common type for the
console, files, and strings, written to standard error, created a custom
writer, indented output, discarded output, and shared a writer between
threads.
Author
List all C# tutorials.