C# ReadLine for Reading File Into List

by Sam Allen - Updated January 7, 2010
File

You want to read a text file into a List or array line-by-line. By processing each line separately, you can apply logic to test the lines for validity or reject them. Here we see how you can read all lines in a file into a List in the C# language.

Using ReadLine

First, we look at the ReadLine method on StreamReader and how you can use it with List. Unfortunately, C# doesn't provide a "Read All Lines" method on StreamReader, but our solution will fill that need. Note that you can use the static File.ReadAllLines method for an array.

=== Program that uses ReadLine and List (C#) ===

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
        const string f = "TextFile1.txt";

        // 1
        // Declare new List.
        List<string> lines = new List<string>();

        // 2
        // Use using StreamReader for disposing.
        using (StreamReader r = new StreamReader(f))
        {
            // 3
            // Use while != null pattern for loop
            string line;
            while ((line = r.ReadLine()) != null)
            {
                // 4
                // Insert logic here.
                // ...
                // "line" is a line in the file. Add it to our List.
                lines.Add(line);
            }
        }

        // 5
        // Print out all the lines.
        foreach (string s in lines)
        {
            Console.WriteLine(s);
        }
    }
}

=== Output of the program ===
    (Prints contents of TextFile1.txt)

This is a text file I created,
Just for this article.

Overview of the preceding example. It declares a new List. List is a generic object that can expand to fit the size of data you read. The List data structure will easily accommodate files from 0 to 1,000,000+ lines long, so it is perfect here.

Using StreamReader. The classes we use are the StreamReader object and the List generic. We use the using keyword to read the files into a List generic. This provides automatic disposal of the object, releasing important resources.

(See Using StreamReader.)

While loop. It uses 'while' with ReadLine. The syntax for ReadLine is a bit complicated. It first assigns the string to the ReadLine result string. That string will be null if we are done reading the file. In C#, you have to have a Boolean result for an if statement, so we test against null.

List usage. You see the Add method call on the instance of List here. This appends another string to the List. It displays the results to the console. You will see all the lines in the file displayed here. This can catch some really simple bugs, such as those caused by an invalid filename.

Catching IOException

You will want to catch IOException here if your application's stability is critical. You could simply catch all I/O exceptions and return an empty array if the file cannot be read. You may have more detailed requirements, but IOException works well here.

Question

What advantages does this have?

It gives you a chance to test each line, as with a regular expression, before adding it to the array. You could use File.ReadAllLines to consume the file into an array, but you can't test each line first that way.

(See File Handling.)

Using arrays instead. When you are done with the testing of the file line-by-line with ReadLine, and have added all the correct lines to the List, you can convert the List to an array, as with ToArray().

(See Convert List to Array.)

Summary

We saw here a common approach of reading each line into a file line-by-line. This can provide superior memory management over allocating an entire array, and offers an opportunity for you to test each line before storing it.

(Do not copy this page.)

Dot Net Perls | Search
Files | File Handling | Path Examples | Recursive File and Directory Method | Using StreamReader | Using StreamWriter
C# | SaveFileDialog Tutorial | IntegralHeight Property (Windows Forms) | Array.FindIndex Method | File.Replace Method
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen