Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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( ); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata