Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no System.IO.File.ReadLines(file).Count() in .Net 4?

Tags:

c#

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

like image 597
Eyalk Avatar asked Jun 20 '12 22:06

Eyalk


People also ask

What is the use of readline in File Explorer?

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.

What is the difference between readlines and readalllines methods?

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.

What does readalllines do in Python?

ReadAllLines(String) ReadAllLines(String) ReadAllLines(String) ReadAllLines(String) Opens a text file, reads all lines of the file, and then closes the file.

How to count the number of lines in a text 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:


2 Answers

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

like image 166
Samuel Slade Avatar answered Sep 19 '22 18:09

Samuel Slade


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

like image 27
infojolt Avatar answered Sep 20 '22 18:09

infojolt