How is it possible to know the number of lines from a text file? Now I find out like this:

int count = System.IO.File.ReadAllLines(path_base).Length; 

But this method takes a lot of time and clogs up RAM, when loading text files larger than 1 gigabyte, this is not relevant.

  • Use ReadLines or if you want to spend directly a minimum of resources, then read from the buffer , read large files - with this you can simply count the number of newlines in the file - tym32167
  • int count = System.IO.File.ReadAllLines (path_base) .Count (); using System.Linq, but here you need to take into account that for 32 bit systems the maximum file is 4Gb, it is better to use the option from the answer below - B. Vandyshev

2 answers 2

Example with 10 megabyte buffer.

 var linesCount = 1; int nextLine = '\n'; using (var streamReader = new StreamReader( new BufferedStream( File.OpenRead(@"D:\temp\11.xml"), 10 * 1024 * 1024))) // буфер в 10 мегабайт { while(!streamReader.EndOfStream) { if (streamReader.Read() == nextLine) linesCount++; } } Console.WriteLine(linesCount); 
  • one
    instead of '\ n' it is better to use Enviroment . NewLine - B. Vandyshev
  • @ B.Vandyshev Enviroment.NewLine is a string, not a character. I can not compare when reading a string and character. In addition, in Windows it is \r\n , in Linux \n , that is, \n present in any case, regardless of what end of the lines the file is saved with. - tym32167
  • @ tym32167, but in a poppy like \r ? - Grundy
  • @Grundy about the poppy unfortunately I do not know - tym32167
  • one
    @Grundy well and great, then the answer does not have to edit :) - tym32167
  int count = 0; string line; TextReader reader = new StreamReader(path_base); while ((line = reader.ReadLine()) != null) { count++; } reader.Close(); 
  • one
    File.ReadLines(path).Count() - is equivalent to your code. The ReadLines method does not read the entire file at once, unlike ReadAllLines . - Alexander Petrov
  • And if the file is large (gigabytes) and consists of a single line? Bummer ... If you need a solution that works on any input data, then you need to read the file in blocks and look for the end of line characters in them. - Alexander Petrov
  • @AlexanderPetrov can tell how to implement it? To find the end of the line at the end? - win8de
  • Why do you need to save stock in line? Not wrapping IDisposable in using is not very good - B. Vandyshev