How to know the number of lines a large file has in C #?

5

Well, I'm starting now in C #, but I already have a great experience with PHP and I know more or less Python .

And the means I use to understand is to do something that I found difficult to do in a language I know in a language I do not know about.

I asked here how to count the lines of a large file in PHP, as it is something that is not so simple to do in the language, does not have a specific function for it, I have to do maneuvers.

Now that I'm learning C# , I'd like to know how do I know how many lines a large file has.

But I would like every function used to be explained, because I do not understand much of C # yet.

I want to read a JSON of 6.6MB here from my machine and know how many lines it has through C #.

How can I do this?

    
asked by anonymous 13.05.2016 / 19:11

2 answers

6

The class File ( System.IO.File ) has a method ReadLines . .

It does a lazy loading of the lines of the file, that is, a certain line will only be loaded into memory when requested.

So you can do:

var qtdLinhas = File.ReadLines("C:\Users\Wallace\arquivo.json").Count();
    
13.05.2016 / 19:16
5

More manually, you could also use this algorithm (Also working with System.IO) ...

In Stream Peek returns the next character, without advancing the Stream pointer ... and if there are no more characters it returns -1, so I took advantage of it to use it in the while ... at least in my tests (I do not have no 6mb file) my algorithm took half a millisimo to read a text file with 103kb ... how much the File.ReadLine took 22 thousandths ...

Well,bothalgorithmsworkwell,withgreatperformance,it'suptoyoutochoose...

stringfilename="c:\input.txt"
TextReader Leitor = new StreamReader(filename, true);//Inicializa o Leitor
int Linhas = 0;
while (Leitor.Peek() != -1) {//Enquanto o arquivo não acabar, o Peek não retorna -1 sendo adequando para o loop while...
    Linhas++;//Incrementa 1 na contagem
    Leitor.ReadLine();//Avança uma linha no arquivo
}
Leitor.Close(); //Fecha o Leitor, dando acesso ao arquivo para outros programas....
Console.WriteLine("Este Arquivo contém " + Linhas + " Linhas.");
Console.ReadKey();
    
13.05.2016 / 19:55