December 2007
Intermediate to advanced
896 pages
19h 57m
English
You need to count lines of text within a string or within a file.
Use the LineCount method shown in Example 10-6 to read in the entire file and count the number of line feeds.
Example 10-6. LineCount 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)
{
using (FileStream FS = new FileStream(source, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
using (StreamReader SR = new StreamReader(FS))
{
text = SR.ReadToEnd( );
}
}
}
Regex RE = new Regex("\n", RegexOptions.Multiline);
MatchCollection theMatches = RE.Matches(text);
if (isFileName)
{
return (theMatches.Count);
}
else
{
return (theMatches.Count) + 1;
}
}
else
{
// Handle a null source here.
return (0);
}
}LineCount2, a better-performing alternate 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, as shown in Example 10-7.
Example 10-7. LineCount2 method
public static long LineCount2(string source, bool isFileName) { if (source != null) { string text = source; long numOfLines = 0; if (isFileName) { using (FileStream FS = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (StreamReader SR = new StreamReader(FS)) { while (text != null) { text = SR.ReadLine( ); if (text != null) { ++numOfLines; } } } } return (numOfLines); } else ...Read now
Unlock full access