O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.9. Counting Lines of Text

Problem

You need to count lines of text within a string or within a file.

Solution

Read in the entire file and count the number of linefeeds, as shown in the following method:

using System;
using System.Text.RegularExpressions;
using System.IO;

public static long LineCount(string source, bool isFileName)
{
    if (source != null)
    {
        string text = source;

        if (isFileName)
        {
            FileStream FS = new FileStream(source, FileMode.Open, 
                                         FileAccess.Read, FileShare.Read);
            StreamReader SR = new StreamReader(FS);
            text = SR.ReadToEnd( );
            SR.Close( );
            FS.Close( );
        }

        Regex RE = new Regex("\n", RegexOptions.Multiline);
        MatchCollection theMatches = RE.Matches(text);

        // Needed for files with zero length
        //   Note that a string will always have a line terminator 
        //        and thus will always have a length of 1 or more
        if (isFileName)
        {
            return (theMatches.Count);
        }
        else
        {
            return (theMatches.Count) + 1;
        }
    }
    else
    {
        // Handle a null source here
        return (0);
    }
}

An alternative version of this method uses the StreamReader.ReadLine method to count lines in a file and a regular expression to count lines in a string:

public static long LineCount2(string source, bool isFileName) { if (source != null) { string text = source; long numOfLines = 0; if (isFileName) { FileStream FS = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read); StreamReader SR = new StreamReader(FS); while (text != null) { text = SR.ReadLine( ); if (text != null) { ++numOfLines; } } SR.Close( ); FS.Close( ); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required