StreamReader and StreamWriter
StreamReader and StreamWriter read and write text one piece at a time, like reading a book page by page or writing a diary line by line. They suit big files that should not be loaded at once.
In this page:
Syntax
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("text");
}
using (StreamReader reader = new StreamReader(path))
{
string line = reader.ReadLine();
}
StreamReader and StreamWriter
StreamReader and StreamWriter read and write text incrementally rather than all at once, which is more memory-efficient for large files.
StreamReader.ReadLine() reads one line at a time until it returns null at end-of-file. Both implement IDisposable, so they should be wrapped in a using block.
Note:
Use
StreamReader.ReadLine() in a while loop to process a large file one line at a time.Example: StreamReader and StreamWriter
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = "lines.txt";
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("line one");
writer.WriteLine("line two");
}
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Not wrapping a
StreamWriterin ausingblock or callingDispose, so buffered text may never be flushed to the file and the file stays locked. - Creating
new StreamWriter(path)for an existing file and losing its old contents, since it overwrites by default; passappend: trueto add to it. - Calling
ReadLine()without checking for the end, when it returnsnullafter the last line; loop untilnullorreader.EndOfStream.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: