Home >Backend Development >C++ >What's the Most Efficient Way to Count Lines in a C# Text File?

What's the Most Efficient Way to Count Lines in a C# Text File?

DDD
DDDOriginal
2025-01-11 08:36:44421browse

What's the Most Efficient Way to Count Lines in a C# Text File?

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)

The

File.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!

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