Dot Net Perls
C#

ReadLine for Reading File Into Array

by Sam Allen

Problem

Read a text file into an array or list containing its individual lines. You have a text file on the disk you want to read into your program. We must collect all the lines in the text file (read about text file handling), put each in a string, and then store the result in memory. We may require a plain string[] array, or a List generic.

Solution: C#

We will use StreamReader objects for the solution code. Unfortunately, C# doesn't provide a "Read All Lines" method on a StreamReader, but our solution will fill that need. The next two methods are easily used in your code and will perform these functions well.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

/// <summary>
/// Example class for reading files in by lines and storing the results.
/// </summary>
class ReadLineExample
{
    /// <summary>
    /// Read in a file line-by-line, and store it all in a List.
    /// You can then use the List to look at the contents of the
    /// file without having to open the file again.
    /// </summary>
    /// <param name="fileName">The file name you wish to open.</param>
    /// <returns>The list containing all lines in the file.</returns>
    static public List<string> ReadFileLines(string fileName)
    {
        try
        {
            List<string> allLines = new List<string>();
            using (StreamReader reader = new StreamReader(fileName))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    //
                    // "line" is a line in the file. Add it to our List.
                    //
                    allLines.Add(line);
                }
            }
            return allLines;
        }
        catch (IOException)
        {
            //
            // If the file isn't available, it is basically empty,
            // so return an empty list.
            //
            return new List<string>();
        }
    }

    /// <summary>
    /// Read all lines in the file to an array and return it.
    /// </summary>
    /// <param name="fileName">The file you want to read in.</param>
    /// <returns>The string array containing all the lines in the file.</returns>
    static public string[] ReadFileLinesString(string fileName)
    {
        //
        // Simply use our method to read in the file lines into a List,
        // and then convert that to an array.
        //
        return ReadFileLines(fileName).ToArray();
    }
}
  1. In first method
    The first method performs the work into reading the entire file and storing it in a List.
  2. StreamReader and List are used
    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. The List data structure will easily accomodate files from 0 to 1,000,000+ lines long, so it is perfect here. The two objects are optimized in the framework for this purpose.
  3. While ReadLine
    The syntax for ReadLine I use 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.
  4. IOException is caught
    Exception handling is very difficult, but these methods 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.

List and Array

In C#, an array is much slower and harder to resize than a List, so we simply use the List always when reading in the file. When we want to get a string[] array from the file, we use the List method and convert it to an array afterwards. This is not an inefficient method, but different and possibly faster solutions may be available.

Calling Convention

As always, we want some specific examples of how to use the above class. Fortunately, it is very simple. Note that the above class is static, which means it saves state and we don't need to use new at all. Here is how to call the methods above in other parts of your code.

class Program
{
    static void Main(string[] args)
    {
        //
        // Read in the lines from the file and store in a List.
        // Print out the Count property value.
        //
        List<string> lines = ReadLineExample.ReadFileLines("line-test.txt");
        Console.WriteLine(lines.Count.ToString() + " lines in file");

        //
        // Read in the lines from the file and store in an array of strings.
        //
        string[] linesArray = ReadLineExample.ReadFileLinesString("line-test.txt");
        Console.WriteLine(linesArray.Length.ToString() + " lines in file");
    }
}

Conclusion

Use these static methods for an easy way to read the lines of a file into an array or List. They share most of their code and can be called most anywhere with no fuss. They provide XML comments for reminders of how to use them. As always, reuse as much code as you can, including methods such as these.

© 2008 Sam Allen. All rights reserved.

Ads by The Lounge