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

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.
Syntax
csharp
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

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);
            }
        }
    }
}
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
  1. Not wrapping a StreamWriter in a using block or calling Dispose, so buffered text may never be flushed to the file and the file stays locked.
  2. Creating new StreamWriter(path) for an existing file and losing its old contents, since it overwrites by default; pass append: true to add to it.
  3. Calling ReadLine() without checking for the end, when it returns null after the last line; loop until null or reader.EndOfStream.
🔒

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.