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
File.ReadLines, added recently in the .NET Framework, loads each line of a file into a String. It does not process the entire file at once. Its effect can be duplicated with a StreamReader instance and its ReadLine Function.
The caller does not have the required permission. Use this method to specify an encoding to use read the file. The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned.
ReadAllLines(String) ReadAllLines(String) ReadAllLines(String) ReadAllLines(String) Opens a text file, reads all lines of the file, and then closes the file.
The simplest way to get the number of lines in a text file is to combine the File.ReadLines method with System.Linq.Enumerable.Count. The ReadLines method returns an IEnumerable<string> on which we can then call the Count method to get the result. Here's how:
Count<T>()
is an extension method for objects of IEnumerable<T>
. Try adding a using
statement for the namespace System.Linq
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With