BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 2.0+

Counting the Lines in a Text File

The number of lines in a source code file can be used as a crude measure of program complexity or developer productivity. In a CSV file, the number of lines may represent the number of records stored. This article explains how to determine this number.

Counting Lines

A common, though rather poor, measure of the complexity of a program or a developer's productivity can be obtained by counting the lines of source code. If you wish to determine the number of lines in a text file, you can achieve this easily using several static methods from the File class, which may be found in the System.IO namespace. In this short article we will examine two ways that you can obtain a line count for an existing text file.

As we will be using the File class, add the following using directive at the top of your code to simplify calls to the class's members.

using System.IO;

Using File.ReadAllLines

A very simple way to obtain a line count for a text file is using the ReadAllLines method. This method reads an entire text file into an array of strings. Each string represents a single line of text, so reading the Length property of the array returns the total line count. Although simple, you should use this with care as loading very large files will use a lot of memory unnecessarily. It is also possible that there will not be enough memory available to load the entire text, causing an exception to be thrown.

int count = File.ReadAllLines(@"c:\Test\TextFile.txt").Length;

Using a Stream

When working with larger files, it is more efficient to read the text file using a StreamReader. You can open the file for reading, then read the text one line at a time using the StreamReader's ReadLine method. This returns the next line from the file, or a null reference when the text is exhausted. By repeatedly executing ReadLine within a while loop, you can count the lines with an incrementing variable, as in the following sample code:

int count = 0;
using (StreamReader reader = File.OpenText(@"c:\Test\TextFile.txt"))
{
    while (reader.ReadLine() != null)
    {
        count++;
    }
}
24 June 2010