Home >Backend Development >C++ >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#.
<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.
<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.
<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!