Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

The StreamReader and StreamWriter classes

Reference for StreamReader and StreamWriter in C#: read text line by line, write text, encodings and BOM, async methods, flushing, leaveOpen and disposal.

StreamReader and StreamWriter read and write text on top of a byte Stream. They handle the encoding (UTF-8 by default), the buffering and the line breaks, so you work with strings and characters instead of bytes. You can create them from a file path, which opens a FileStream internally, or from any stream such as a MemoryStream or a network stream.

Use them when the one-call File.ReadAllText and File.WriteAllText methods are not suitable: files too large to hold in memory, data produced a piece at a time, or text that travels over a stream. The in-memory counterparts StringReader and StringWriter have the same members and read from or write to a string.

C#
using var writer = new StreamWriter("log.txt");
writer.WriteLine("started");

Try it

C# Write lines, read them back

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# Encodings, line endings and async

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 StreamReader(string path);
public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks = true);
public StreamReader(Stream stream, Encoding? encoding = null, bool detectEncodingFromByteOrderMarks = true,
                    int bufferSize = -1, bool leaveOpen = false);

public StreamWriter(string path);
public StreamWriter(string path, bool append);
public StreamWriter(string path, bool append, Encoding encoding);
public StreamWriter(Stream stream, Encoding? encoding = null, int bufferSize = -1, bool leaveOpen = false);
Member Description
ReadLine() / ReadLineAsync() Next line without the terminator, or null at the end.
ReadToEnd() The rest of the text as one string.
Read() / Read(char[], int, int) One character (-1 at the end) or a block of characters.
Peek() The next character without consuming it, -1 at the end.
EndOfStream true when nothing is left (may block on network streams).
CurrentEncoding The encoding actually in use (changes if a BOM is detected).
Write(...), WriteLine(...) Write values using ToString(), or a composite format string. Async versions exist.
NewLine The line terminator used by WriteLine (Environment.NewLine by default; settable).
AutoFlush When true, every write is flushed to the stream (slower). Default false.
Flush() Pushes buffered text to the underlying stream.
BaseStream The underlying stream.

Errors: FileNotFoundException, DirectoryNotFoundException, UnauthorizedAccessException, IOException (file in use), ObjectDisposedException (used after disposal), ArgumentNullException.

Usage notes

  • Dispose the writer, always. A StreamWriter buffers text; unless you call Flush() or dispose it (using), the last part of the output can be lost.
  • Disposing closes the underlying stream (even one you passed in), unless you pass leaveOpen: true. After using (var w = new StreamWriter(ms)) { ... } the MemoryStream is closed and unusable; ToArray() still works.
  • Encoding. The default is UTF-8. StreamWriter writes no BOM by default but Encoding.UTF8 does write one, which surprises Unix tools. Use new UTF8Encoding(false) to be explicit. StreamReader detects BOMs for UTF-8, UTF-16 and UTF-32 unless you turn detection off.
  • Line endings. WriteLine uses Environment.NewLine; set NewLine = "\n" for consistent output across platforms. ReadLine understands all common terminators.
  • Process big files line by line with a while ((line = reader.ReadLine()) is not null) loop, or File.ReadLines, which is built on the same reader.
  • EndOfStream versus null. Prefer testing the result of ReadLine() for null. EndOfStream can block on streams that wait for data, and it does an extra buffer check.
  • Do not mix StreamReader with direct reads from the same stream. The reader buffers ahead, so the stream position is no longer where the reader is.
  • Async I/O is useful for network and server code. For files, open them with useAsync (via FileStreamOptions/FileOptions.Asynchronous) to get fully asynchronous operations; the plain StreamReader(path) constructors use a synchronous file handle.
  • Performance. Both classes use an internal buffer (4 KB to 16 KB, adjustable with bufferSize). Call Write many times without worry; call Flush only when another reader needs the data right away (a log you tail, a pipe).
  • Not thread-safe. Wrap with TextWriter.Synchronized(writer) if several threads must write to the same writer.