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.
using var writer = new StringWriter(); writer.WriteLine("Hello"); writer.Write(42); string text = writer.ToString();
Try it
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.
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
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 asRender(TextWriter output)serves the console, files, HTTP responses and tests alike. - Subclassing is cheap. Overriding
EncodingandWrite(char)is enough; every otherWriteoverload funnels into it. OverrideWrite(string)andWrite(char[], int, int)too if performance matters. - Dispose file writers.
StreamWriterbuffers its output. WithoutDispose()orFlush(), the last bytes may never reach the file.StringWriterholds no resources, but disposing it is harmless and keeps analyzers quiet. - Culture. The
StringWriter(IFormatProvider)constructor setsFormatProvider, which decides decimal separators. PassCultureInfo.InvariantCulturewhen the text is parsed by a machine later. - Thread safety. A plain
TextWriteris not thread-safe.TextWriter.Synchronized(writer)makes single calls atomic, but two consecutiveWriteLinecalls from different threads can still interleave their lines. - Newline portability.
WriteLineon Windows writes\r\nby default. SetNewLinebefore writing if the output must be identical across systems, for example in golden-file tests. - Capturing the console.
Console.SetOut(new StringWriter())redirects allConsole.WriteLinecalls; restore the original writer afterwards. - Reading counterparts.
TextReader,StringReaderandStreamReadermirror these classes on the input side.