Home >Backend Development >C++ >How Can I Efficiently Count Lines in a C# Text File?

How Can I Efficiently Count Lines in a C# Text File?

DDD
DDDOriginal
2025-01-11 07:07:421006browse

How Can I Efficiently Count Lines in a C# Text File?

C# text file line count counting method

Counting the number of lines in a text file is a common programming task. This article will explore several ways to achieve this in C#.

  • Use the ReadAllLines() method:
<code class="language-csharp">var lineCount = File.ReadAllLines(@"C:\file.txt").Length;</code>

This method reads all lines into an array, which is more efficient for small files. However, for large files, it can consume a lot of memory.

  • Use the ReadLine() method to combine counters:
<code class="language-csharp">var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while (reader.ReadLine() != null)
    {
        lineCount++;
    }
}</code>

This method reads the file line by line and increments the counter. It is more memory efficient, but may be slower for very large files.

  • Use the ReadLines() and Count() methods (.NET 4.0 and above):
<code class="language-csharp">var lineCount = File.ReadLines(@"C:\file.txt").Count();</code>

This method (available in .NET 4.0 and above) delays enumeration without loading the entire file into memory. It strikes a balance between efficiency and memory usage.

The above is the detailed content of How Can I Efficiently Count Lines in a C# Text File?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn