C# StreamWriter
last modified November 6, 2026
In this article we show how to write text with the StreamWriter
class in C#.
StreamWriter from the System.IO namespace writes
characters to a byte stream. It encodes the text, UTF-8 by default, and
collects it in a buffer that is written to the stream when it fills up, when we
call Flush, or when the writer is disposed. It derives from
TextWriter, which also has the StringWriter subclass
for writing to strings.
A StreamWriter can be created from a file path or from any
writable Stream. Disposing it flushes the buffer and closes the
stream under it, unless we ask it to leave the stream open.
Writing to a file
The first example writes a few lines to a text file.
using (var writer = new StreamWriter("words.txt"))
{
writer.WriteLine("sky");
writer.WriteLine("blue");
writer.Write("forest");
writer.Write(' ');
writer.WriteLine(42);
}
Console.Write(File.ReadAllText("words.txt"));
Console.WriteLine($"File size: {new FileInfo("words.txt").Length} bytes");
File.Delete("words.txt");
Created with a path, the writer creates the file, or truncates it if it exists.
writer.Write("forest");
writer.Write(' ');
writer.WriteLine(42);
Write adds text without a line terminator and
WriteLine adds one after it. Both have overloads for strings,
characters, numbers, and other types, which are converted to text.
The 19 bytes are 16 characters plus three newlines. On Linux,
WriteLine ends lines with \n; on Windows with
\r\n.
$ dotnet run sky blue forest 42 File size: 19 bytes
Appending to a file
The append parameter decides whether existing content is kept.
for (int run = 1; run <= 3; run++)
{
using var writer = new StreamWriter("log.txt", append: true);
writer.WriteLine($"run {run} at step {run * 10}");
}
Console.Write(File.ReadAllText("log.txt"));
using (var writer = new StreamWriter("log.txt"))
{
writer.WriteLine("overwritten");
}
Console.Write(File.ReadAllText("log.txt"));
File.Delete("log.txt");
We open the log file three times in append mode, each time adding one line.
using var writer = new StreamWriter("log.txt", append: true);
With append: true, the writer creates the file if needed and
starts writing at its end. A using declaration inside the loop
body disposes the writer at the end of each iteration.
using (var writer = new StreamWriter("log.txt"))
Without the parameter, the file is truncated, so only the new line remains.
$ dotnet run run 1 at step 10 run 2 at step 20 run 3 at step 30 overwritten
Encoding and the byte order mark
A writer created without an encoding writes UTF-8 without a byte order mark
(BOM). The static Encoding.UTF8 property, however, is an encoding
that does emit one.
using System.Text;
Write("default.txt", null);
Write("utf8.txt", Encoding.UTF8);
Write("utf8nobom.txt", new UTF8Encoding(false));
Write("utf16.txt", Encoding.Unicode);
void Write(string path, Encoding? encoding)
{
using (var writer = encoding is null
? new StreamWriter(path)
: new StreamWriter(path, false, encoding))
{
writer.Write("\u017Eiv\u00E9");
}
byte[] bytes = File.ReadAllBytes(path);
Console.WriteLine($"{path,-14} {bytes.Length,2} bytes {Convert.ToHexString(bytes)}");
File.Delete(path);
}
We write the Slovak word živé with four encodings and print the bytes of each file.
: new StreamWriter(path, false, encoding))
The second parameter is append; the third is the encoding.
The default and new UTF8Encoding(false) give the same six bytes:
ž and é take two bytes each in UTF-8.
Encoding.UTF8 adds the three-byte BOM EF BB BF.
UTF-16 starts with the BOM FF FE and uses two bytes per
character.
Readers detect the BOM, so it does no harm to .NET programs, but some tools, for example Unix shells reading a script, treat it as part of the text.
$ dotnet run default.txt 6 bytes C5BE6976C3A9 utf8.txt 9 bytes EFBBBFC5BE6976C3A9 utf8nobom.txt 6 bytes C5BE6976C3A9 utf16.txt 10 bytes FFFE7E0169007600E900
Formatted output
Interpolated strings with alignment and format specifiers produce text columns. Numbers and dates are formatted with the current culture.
using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("de-DE");
(string Name, decimal Price, int Qty)[] items =
[
("pen", 1.2m, 10),
("notebook", 3.75m, 4),
("backpack", 49.9m, 1),
];
using (var writer = new StreamWriter("invoice.txt"))
{
writer.WriteLine($"{"Item",-10}{"Price",8}{"Qty",5}{"Total",10}");
foreach (var (name, price, qty) in items)
{
writer.WriteLine($"{name,-10}{price,8:F2}{qty,5}{price * qty,10:F2}");
}
writer.WriteLine("Date: {0:d}", new DateTime(2026, 11, 6));
writer.WriteLine(string.Create(CultureInfo.InvariantCulture,
$"Sum (invariant): {items.Sum(e => e.Price * e.Qty):F2}"));
}
Console.Write(File.ReadAllText("invoice.txt"));
File.Delete("invoice.txt");
We set the culture to German and write a small invoice.
writer.WriteLine($"{name,-10}{price,8:F2}{qty,5}{price * qty,10:F2}");
A negative alignment pads on the right, so names are left-aligned; positive
values right-align the numbers. F2 gives two decimals, with a
comma as the German decimal separator.
writer.WriteLine("Date: {0:d}", new DateTime(2026, 11, 6));
WriteLine also accepts a composite format string, like
string.Format. The short date format is culture-specific too.
writer.WriteLine(string.Create(CultureInfo.InvariantCulture,
$"Sum (invariant): {items.Sum(e => e.Price * e.Qty):F2}"));
For data files that other programs read, use the invariant culture.
string.Create with a format provider formats an interpolated
string with that culture.
$ dotnet run Item Price Qty Total pen 1,20 10 12,00 notebook 3,75 4 15,00 backpack 49,90 1 49,90 Date: 06.11.2026 Sum (invariant): 76.90
Flushing the buffer
Written text stays in the buffer of the writer until it is flushed.
var writer = new StreamWriter("data.txt");
writer.WriteLine("first line");
Console.WriteLine($"After WriteLine: {Size()} bytes");
writer.Flush();
Console.WriteLine($"After Flush: {Size()} bytes");
writer.AutoFlush = true;
writer.WriteLine("second line");
Console.WriteLine($"With AutoFlush: {Size()} bytes");
writer.Dispose();
File.Delete("data.txt");
long Size() => new FileInfo("data.txt").Length;
We check the size of the file after each step.
writer.Flush();
After WriteLine, the file is still empty. Flush
encodes the buffered characters and writes them to the stream.
writer.AutoFlush = true;
With AutoFlush, the writer flushes after every write call. This
is useful for log files that other processes watch, but it makes many small
writes slower.
$ dotnet run After WriteLine: 0 bytes After Flush: 11 bytes With AutoFlush: 23 bytes
Forgetting to dispose
StreamWriter has no finalizer. If it is never disposed or
flushed, the buffered text is lost.
Write();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine($"File size: {new FileInfo("lost.txt").Length} bytes");
File.Delete("lost.txt");
static void Write()
{
var writer = new StreamWriter("lost.txt");
for (int i = 0; i < 100; i++)
{
writer.WriteLine($"line {i}");
}
}
The Write method writes 100 lines and returns without disposing
the writer. Then we force a garbage collection.
The file stream under the writer is closed by its own finalizer, but the
writer's buffer is never written. All 100 lines are lost and the file is
empty. Always create writers with using.
$ dotnet run File size: 0 bytes
Line endings
The NewLine property sets the terminator that
WriteLine appends. It defaults to
Environment.NewLine.
using var ms = new MemoryStream();
using (var writer = new StreamWriter(ms, leaveOpen: true))
{
writer.WriteLine("a");
writer.NewLine = "\r\n";
writer.WriteLine("b");
writer.Write("c\n");
}
Console.WriteLine(BitConverter.ToString(ms.ToArray()));
Console.WriteLine($"Environment.NewLine: {BitConverter.ToString(
System.Text.Encoding.ASCII.GetBytes(Environment.NewLine))}");
We write to a memory stream and print the bytes.
writer.NewLine = "\r\n";
After this assignment, WriteLine ends lines with
0D 0A. This is useful for network protocols such as HTTP and
SMTP, which require \r\n on every platform.
writer.Write("c\n");
NewLine only affects WriteLine. A \n
inside the text is written as it is.
$ dotnet run 61-0A-62-0D-0A-63-0A Environment.NewLine: 0A
Writing to a MemoryStream
A writer over a memory stream builds encoded text in memory, for example before sending it over a network.
using System.Text;
using var ms = new MemoryStream();
using (var writer = new StreamWriter(ms, Encoding.UTF8, leaveOpen: true))
{
writer.WriteLine("id=7");
writer.WriteLine("name=falcon");
}
Console.WriteLine($"Length: {ms.Length} bytes");
Console.WriteLine($"BOM: {Convert.ToHexString(ms.GetBuffer(), 0, 3)}");
ms.Position = 0;
using var reader = new StreamReader(ms);
Console.Write(reader.ReadToEnd());
We write two lines with an explicit Encoding.UTF8 and read them
back.
using (var writer = new StreamWriter(ms, Encoding.UTF8, leaveOpen: true))
leaveOpen keeps the memory stream usable after the writer is
disposed. Disposing is still needed: it flushes the text into the stream.
The 20 bytes include the BOM written by Encoding.UTF8. The
StreamReader recognizes it and does not return it as text.
$ dotnet run Length: 20 bytes BOM: EFBBBF id=7 name=falcon
Asynchronous writing
WriteLineAsync and FlushAsync write without blocking
the calling thread.
var cities = new[] { "Bratislava", "Prague", "Vienna", "Budapest", "Warsaw" };
await using (var writer = new StreamWriter("cities.txt"))
{
foreach (var city in cities)
{
await writer.WriteLineAsync($"{city} ({city.Length})");
}
await writer.FlushAsync();
}
foreach (var line in await File.ReadAllLinesAsync("cities.txt"))
{
Console.WriteLine(line);
}
File.Delete("cities.txt");
We write a list of cities and their name lengths.
await using (var writer = new StreamWriter("cities.txt"))
await using calls DisposeAsync, which flushes the
remaining text asynchronously. A plain using would do the final
flush synchronously.
await writer.FlushAsync();
An explicit FlushAsync before disposing is not required here; it
is shown because it is needed when the writer stays open, for example after
each message in a network protocol.
$ dotnet run Bratislava (10) Prague (6) Vienna (6) Budapest (8) Warsaw (6)
Source
In this article we have written text with StreamWriter: creating
and appending files, choosing encodings, formatting, flushing, setting line
endings, writing to memory, and writing asynchronously.
Author
List all C# tutorials.