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( ); ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.