StreamReader and Writer
Learn stream-based reading and writing with StreamReader and StreamWriter.
Stream reading with StreamReader
The StreamReader class reads a file as a stream: one line or one block at a time. It is used inside a using block; the file is closed automatically when the block ends. Call: using (var sr = new StreamReader("data.txt")) { ... }.
To read one line at a time, call sr.ReadLine(); it returns null at end of file. StreamReader is preferred for large files because it does not load the whole file into memory.
Stream writing with StreamWriter
The StreamWriter class writes to a file as a stream. It is used inside a using block; the file is closed and the buffer flushed automatically when the block ends. Call: using (var sw = new StreamWriter("out.txt")) { sw.WriteLine("Line"); }.
sw.WriteLine writes a line and adds a line break; sw.Write does not. By default StreamWriter overwrites. To append, use the new StreamWriter(path, true) overload; true means append.
Exercise Write with StreamWriter, read with StreamReader
First write two lines with using (var sw = new StreamWriter("note.txt")) { sw.WriteLine("First"); sw.WriteLine("Second"); }. Then open the file with using (var sr = new StreamReader("note.txt")), call sr.ReadLine() in a while loop (until null) and print each line with Console.WriteLine.
Show example solution
First inside using (var sw = new StreamWriter("note.txt")) call two WriteLine methods. Then inside using (var sr = new StreamReader("note.txt")) write while ((line = sr.ReadLine()) != null) Console.WriteLine(line);.
Example solution:
using System;
using System.IO;
class Program
{
static void Main()
{
using (var sw = new StreamWriter("note.txt"))
{
sw.WriteLine("First");
sw.WriteLine("Second");
}
using (var sr = new StreamReader("note.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
Test yourself
-
Why use StreamReader?
- Faster for small files
- Reads large files in chunks, using less memory
- Reads images as well as text
- Auto-creates the file
Show answer
Reads images as well as text — Correct. StreamReader reads large files line by line using little memory; it does not load the whole file.
-
Match each method to its role
- StreamReader
- Reads a stream
- StreamWriter
- Writes a stream
- ReadLine
- Reads one line
- WriteLine
- Writes one line
-
Complete the using block
using (var sr = new ____("data.txt")) { string line = sr.ReadLine(); }Show answer
using (var sr = new StreamReader("data.txt")) { string line = sr.ReadLine(); }