Effective method of counting lines in C# text files
Counting the number of lines in a text file is a common task in programming. Here's how to accomplish this efficiently in C#:
1. Based on file size (inefficient but simple)
TheFile.ReadAllLines
method loads the entire file into an array. Although simple, this method is very memory intensive for large files. For example, working with a 4GB file on a 32-bit system, there may not be enough memory to allocate the array.
<code class="language-csharp">var lineCount = File.ReadAllLines(@"C:\file.txt").Length;</code>
2. Row iteration method (efficient)
Use a File.OpenText
and while
loop to iterate over the file line by line, incrementing the counter. This method is more efficient than ReadAllLines
and does not require allocating large arrays in memory.
<code class="language-csharp">var lineCount = 0; using (var reader = File.OpenText(@"C:\file.txt")) { while (reader.ReadLine() != null) { lineCount++; } }</code>
Performance and memory considerations:
ReadAllLines
For small files it may be faster due to optimizations, but for large files it will become significantly slower due to memory allocation. On the other hand, OpenText
iteration is more efficient in terms of memory usage, but its performance relative to ReadAllLines
depends on file size and system architecture.
The above is the detailed content of What's the Most Efficient Way to Count Lines in a C# Text File?. For more information, please follow other related articles on the PHP Chinese website!