Problem. You want to count lines in text data with Regex and string-handling methods. You need this for using web server logs or CSV files, or even for text generated by bloggers in a database. Solution. Here we look at how you can count lines in a text file using the C# programming language, reading the file in and counting at the same time.
First, when using large files it is more memory-efficient not to store the entire file contents in RAM at once, and for web server log files, you need efficiency. This next block of code counts the lines in a file on the disk. It does this by using the parameterless ReadLine instance method offered by the StreamReader class in the System.IO namespace. The CountLinesInFile method is static because it stores no state.
=== Program that counts file lines (C#) ===
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 in.</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;
}
}
=== Output of the program ===
(Number of lines in text.txt)Description of the code. It uses StreamReader, which is a useful class for reading in files quickly. It has the useful ReadLine method, which tells the framework to read until the next line break in the file. It increments the count, which contains the number of lines in the file. Finally, the integral variable containing the count is returned. [C# Using StreamReader - dotnetperls.com]
Sometimes, you have the entire text in the program's memory in the form of a string. In this case, you can use the string-based line-counting methods provided in a separate article on this site. The methods are tested there as well. [C# Line Count String Methods - dotnetperls.com]
Here we saw how you can count the number of lines in files by using StreamReader and ReadLine. Additionally, we looked at the ReadLine method and discussed other ways of counting lines in text data using the C# language.