Strings in C# programs often contain many lines. And it is sometimes necessary to count these lines. This is needed for server logs and CSV files.
We can use Regex
and string
-handling methods. For files, we can use StreamReader
and ReadLine
—these are part of the System.IO
namespace.
First, when using large files it is more memory-efficient not to store the entire file contents in RAM at once. This next block of code counts the lines in a file on the disk.
ReadLine
instance method offered by the StreamReader
class
in the System.IO
namespace.CountLinesInFile
is static
because it stores no state. It contains the logic for counting lines in a file.StreamReader
, which is a useful class
for reading in files quickly. It has the useful ReadLine
method.int
containing the count is returned.using System.IO; class Program { static void Main() { CountLinesInFile("test.txt"); } /// <summary> /// Count the number of lines in the file specified. /// </summary> /// <param name="f">The filename to count lines.</param> /// <returns>The number of lines in the file.</returns> static long CountLinesInFile(string f) { long count = 0; using (StreamReader r = new StreamReader(f)) { string line; while ((line = r.ReadLine()) != null) { count++; } } return count; } }(Number of lines in text.txt)
Here is the string
-based method. Also, we see the regular expression based method, which requires the System.Text.RegularExpressions
namespace. The methods have the same result.
IndexOf
method. It finds all the newline characters.MatchCollection
. This method uses the Matches
method with RegexOptions.Multiline
.using System; using System.Text.RegularExpressions; class Program { static void Main() { // Version 1: count lines with IndexOf. long a = CountLinesInString("This is an\r\n awesome website."); Console.WriteLine(a); // Version 2: count lines with Regex. long b = CountLinesInStringSlow("This is an awesome\r\n website.\r\n Yeah."); Console.WriteLine(b); } static long CountLinesInString(string s) { long count = 1; int start = 0; while ((start = s.IndexOf('\n', start)) != -1) { count++; start++; } return count; } static long CountLinesInStringSlow(string s) { Regex r = new Regex("\n", RegexOptions.Multiline); MatchCollection mc = r.Matches(s); return mc.Count + 1; } }2 3
For performance, using Regex
is consistently slower than string
-based loops. Even in .NET 5 for Linux in 2021, this remains true.
We counted the number of lines in files by using StreamReader
and ReadLine
. We also looked at the ReadLine
method and discussed other approaches.