Line Count for FileCount lines in files with StreamReader and a while-loop with a counter.
Line count. 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.
Files. 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.
Tip It does this by using the parameterless ReadLine instance method offered by the StreamReader class in the System.IO namespace.
Detail This method is static because it stores no state. It contains the logic for counting lines in a file.
And It uses StreamReader, which is a useful class for reading in files quickly. It has the useful ReadLine method.
Next It increments the count, which contains the number of lines in the file. Finally the 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)
Strings. 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.
Version 1 This version of the method uses the IndexOf method. It finds all the newline characters.
Version 2 The second method uses 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\nawesome website."); Console.WriteLine(a); // Version 2: count lines with Regex. long b = CountLinesInStringSlow("This is an awesome\r\nwebsite.\r\nYeah."); 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
Performance. For performance, using Regex is consistently slower than string-based loops. Even in .NET 5 for Linux in 2021, this remains true.
A summary. We counted the number of lines in files by using StreamReader and ReadLine. We also looked at the ReadLine method and discussed other approaches.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2023 Sam Allen.