ZetCode

C# StringWriter

last modified November 6, 2026

In this article we show how to use the StringWriter class in C#.

StringWriter from the System.IO namespace is a TextWriter that writes into a StringBuilder. It has the same Write and WriteLine methods as StreamWriter and Console.Out, but the result is a string in memory.

It is used with APIs that write to a TextWriter, such as XmlWriter, to capture console output in tests, and to build text with code that can also write to files.

Building a string

The first example writes a short report into a string.

Program.cs
using var writer = new StringWriter();

writer.WriteLine("Report");
writer.WriteLine(new string('-', 6));
writer.Write("items: ");
writer.WriteLine(3);
writer.Write("ok: ");
writer.Write(true);

string text = writer.ToString();

Console.WriteLine(text);
Console.WriteLine($"Length: {text.Length}");

The Write and WriteLine overloads accept strings, numbers, booleans, and other types.

string text = writer.ToString();

ToString returns the text written so far. The writer stays usable, and later calls return the extended text.

The length of 31 includes three newline characters. The last Write adds no newline, so Console.WriteLine ends the line.

$ dotnet run
Report
------
items: 3
ok: True
Length: 31

The underlying StringBuilder

A StringWriter can write into an existing StringBuilder, and GetStringBuilder gives access to the one it uses.

Program.cs
using System.Text;

var sb = new StringBuilder("Header\n");
using var writer = new StringWriter(sb);

writer.WriteLine("line 1");
writer.WriteLine("line 2");

Console.Write(sb);
Console.WriteLine($"Same builder: {ReferenceEquals(sb, writer.GetStringBuilder())}");

writer.GetStringBuilder().Clear();
writer.Write("reused");

Console.WriteLine(writer.ToString());

The builder already contains a header. The writer appends after it.

Console.WriteLine($"Same builder: {ReferenceEquals(sb, writer.GetStringBuilder())}");

No copy is made; the writer and our variable share one builder.

writer.GetStringBuilder().Clear();

Clearing the builder empties the writer, so it can be reused for the next string.

$ dotnet run
Header
line 1
line 2
Same builder: True
reused

Culture

A StringWriter formats numbers and dates with its format provider. The constructor without arguments uses the current culture.

Program.cs
using System.Globalization;

CultureInfo.CurrentCulture = new CultureInfo("sk-SK");
double value = 1234.5;

using var current = new StringWriter();
using var invariant = new StringWriter(CultureInfo.InvariantCulture);

current.WriteLine(value);
invariant.WriteLine(value);

invariant.WriteLine("{0:N1}", value);
invariant.WriteLine($"{value:N1}");

Console.Write(current);
Console.Write(invariant);

We set a Slovak culture, which uses a decimal comma, and write the same number with two writers.

using var invariant = new StringWriter(CultureInfo.InvariantCulture);

This writer formats with the invariant culture, both in WriteLine(double) and in composite format strings such as "{0:N1}".

invariant.WriteLine($"{value:N1}");

An interpolated string is different. It is turned into a string with the current culture before WriteLine receives it, so the writer's culture has no effect. The last line has the Slovak decimal comma and a no-break space as the group separator. Use a format string, or string.Create with a provider, when the culture matters.

$ dotnet run
1234,5
1234.5
1,234.5
1 234,5

XML and the encoding property

StringWriter.Encoding returns UTF-16, because .NET strings are UTF-16. XmlWriter puts this encoding into the XML declaration.

Program.cs
using System.Text;
using System.Xml;

var settings = new XmlWriterSettings { Indent = true };

using (var sw = new StringWriter())
{
    using (var xw = XmlWriter.Create(sw, settings))
    {
        WriteDoc(xw);
    }

    Console.WriteLine(sw);
}

using (var sw = new Utf8StringWriter())
{
    using (var xw = XmlWriter.Create(sw, settings))
    {
        WriteDoc(xw);
    }

    Console.WriteLine(sw);
}

static void WriteDoc(XmlWriter xw)
{
    xw.WriteStartDocument();
    xw.WriteStartElement("user");
    xw.WriteAttributeString("id", "1");
    xw.WriteElementString("name", "Anna");
    xw.WriteEndElement();
}

class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

We write the same document twice.

With a plain StringWriter, the declaration says encoding="utf-16". If the string is later saved as UTF-8, the declaration is wrong and some parsers reject the file.

class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

Overriding the Encoding property changes only what the writer reports. The text is still a .NET string, but the declaration now says utf-8.

$ dotnet run
<?xml version="1.0" encoding="utf-16"?>
<user id="1">
  <name>Anna</name>
</user>
<?xml version="1.0" encoding="utf-8"?>
<user id="1">
  <name>Anna</name>
</user>

Capturing console output

Console.SetOut replaces the console's output writer. With a StringWriter, we can test methods that print to the console.

Program.cs
string output = Capture(() => Greet(["Anna", "Peter"]));

Console.WriteLine($"Captured {output.Length} characters:");
Console.Write(output);
Console.WriteLine($"Test passed: {output == "Hello, Anna!\nHello, Peter!\n"}");

static void Greet(string[] names)
{
    foreach (var name in names)
    {
        Console.WriteLine($"Hello, {name}!");
    }
}

static string Capture(Action action)
{
    TextWriter original = Console.Out;
    using var writer = new StringWriter();

    Console.SetOut(writer);

    try
    {
        action();
    }
    finally
    {
        Console.SetOut(original);
    }

    return writer.ToString();
}

Greet writes greetings to the console. Capture runs it with the output redirected.

TextWriter original = Console.Out;

We keep the original writer and restore it in the finally block, so the output goes back to the console even if the action throws.

Console.WriteLine($"Test passed: {output == "Hello, Anna!\nHello, Peter!\n"}");

The expected text uses \n, which is the line ending on Linux and macOS. A portable test would build it with Environment.NewLine.

$ dotnet run
Captured 27 characters:
Hello, Anna!
Hello, Peter!
Test passed: True

One method for strings, files, and the console

A method that writes to a TextWriter works with any writer.

Program.cs
(string Name, int Score)[] players = [("Anna", 92), ("Tom", 78), ("Lucia", 85)];

using var sw = new StringWriter();
WriteReport(sw, players);
string report = sw.ToString();
Console.WriteLine($"Report has {report.Split('\n', StringSplitOptions.RemoveEmptyEntries).Length} lines");

using (var file = new StreamWriter("report.txt"))
{
    WriteReport(file, players);
}
Console.WriteLine($"Same text in file: {File.ReadAllText("report.txt") == report}");
File.Delete("report.txt");

WriteReport(Console.Out, players);

static void WriteReport(TextWriter writer, (string Name, int Score)[] players)
{
    writer.WriteLine($"{"Name",-8}{"Score",5}");

    foreach (var (name, score) in players.OrderByDescending(p => p.Score))
    {
        writer.WriteLine($"{name,-8}{score,5}");
    }
}

WriteReport prints players sorted by score.

static void WriteReport(TextWriter writer, (string Name, int Score)[] players)

We call it with a StringWriter, a StreamWriter, and Console.Out. The text in the string and in the file is identical.

$ dotnet run
Report has 4 lines
Same text in file: True
Name    Score
Anna       92
Lucia      85
Tom        78

Source

StringWriter class

In this article we have used StringWriter to build strings, share a StringBuilder, control the culture and the reported encoding, capture console output, and write the same text to different targets.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.