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.
using var writer = new StreamWriter("log.txt"); writer.WriteLine("started");
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 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
StreamWriterbuffers text; unless you callFlush()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. Afterusing (var w = new StreamWriter(ms)) { ... }theMemoryStreamis closed and unusable;ToArray()still works. - Encoding. The default is UTF-8.
StreamWriterwrites no BOM by default butEncoding.UTF8does write one, which surprises Unix tools. Usenew UTF8Encoding(false)to be explicit.StreamReaderdetects BOMs for UTF-8, UTF-16 and UTF-32 unless you turn detection off. - Line endings.
WriteLineusesEnvironment.NewLine; setNewLine = "\n"for consistent output across platforms.ReadLineunderstands all common terminators. - Process big files line by line with a
while ((line = reader.ReadLine()) is not null)loop, orFile.ReadLines, which is built on the same reader. EndOfStreamversusnull. Prefer testing the result ofReadLine()fornull.EndOfStreamcan block on streams that wait for data, and it does an extra buffer check.- Do not mix
StreamReaderwith 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(viaFileStreamOptions/FileOptions.Asynchronous) to get fully asynchronous operations; the plainStreamReader(path)constructors use a synchronous file handle. - Performance. Both classes use an internal buffer (4 KB to 16 KB, adjustable with
bufferSize). CallWritemany times without worry; callFlushonly 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.