StreamReader and StreamWriter
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: