← Back to C# Course | Chapter 14: File I/O & Streams | Lesson 2 of 6

StreamReader and StreamWriter

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

markup
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);
            }
        }
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.