Pesquisar este blog

domingo, 29 de agosto de 2010

Determine the number of lines within a text file

First option: 
var lineCount = File.ReadAllLines(@"C:\file.txt").Length;
 
Second option: 
var lineCount = 0;
using (var reader = File.OpenText(@"C:\file.txt"))
{
    while (reader.ReadLine() != null)
    {
        lineCount++;
    }
}

The first one loads the entire contents of the file into an array which
means it must allocate at least as much memory as the size of the file.
The second merely loops one line at a time so it never has to allocate
more than one line's worth of memory at a time.

Nenhum comentário:

Postar um comentário