6

I am trying to read the number of lines of a file I found here (stackoverflow) that the best way to read the number of lines in a large file is by using the following code:

int count = System.IO.File.ReadLines(file).Count();

However, I can't make it compile. Does any know what is the problem?

Error 5 'System.Collections.Generic.IEnumerable<string>' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'System.Collections.Generic.IEnumerable<string>' could be found (are you missing a using directive or an assembly reference?)

Thanks, Eyal

asheeshr
  • 4,088
  • 6
  • 31
  • 50
Eyalk
  • 465
  • 1
  • 5
  • 15

3 Answers3

12

Count<T>() is an extension method for objects of IEnumerable<T>. Try adding a using statement for the namespace System.Linq.

Samuel Slade
  • 8,405
  • 6
  • 33
  • 55
3

Could you do:

int count = File.ReadAllLines(@"C:\filepath\file.txt").Length;

EDIT: As pointed out in the comments, this could (will) perform badly for large files. For a similar question with more detailed explanation why, view Determine the number of lines within a text file

Community
  • 1
  • 1
infojolt
  • 5,244
  • 3
  • 40
  • 82
  • 2
    "read the number of lines in a **large file**" If you did `ReadAllLines` it will need to temporarly store the entire file in ram. `ReadLines` only needs to store the current line. – Scott Chamberlain Jun 20 '12 at 22:09
  • Good point. For a large file this would be very inefficient. I have updated my answer to link to a similar question. – infojolt Jun 20 '12 at 22:10
-1

This is count for line from window application in read from text file:

int linecount = System.IO.File.ReadAllLines(@"D:\yfile.txt").Length;
MessageBox.Show(linecount != null && (!string.IsNullOrEmpty(linecount.ToString())) ? linecount.ToString() : "Unable To Count");
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
hog
  • 9
  • 1