Question

System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("C:\\Rooms.txt");
Console.WriteLine(lines.Count());
MessageBox.Show(lines.Count().ToString());
foreach(var line in lines)
{
    // ERROR ON THIS LINE THE NAMESPACE NAME LINE COULD NOT BE FOUND
}

I want to get the content of lines and display in a MessageBox. However I get an error on the foreach

Thanks for the assist.

Was it helpful?

Solution

You need to give the loop variable a type, so change

foreach(line in lines)  

to

foreach(string line in lines) 

Apart from that you will get another exception:

ObjectDisposedException : {"Cannot read from a closed TextReader."}

File.ReadLines does not return a collection, it is similar like a StreamReader, it allows to read the file without reading all into memory first. But it needs an open stream. Once you have "executed" it it is disposed.

So you either have to use File.ReadAllLines which returns a string[] or don't use it twice.

  1. Count()
  2. foreach(line in lines)

From MSDN:

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; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

OTHER TIPS

foreach requires you to specify the type and name of the variable. You only specified line, which it took to be the type. var, which implicitly types the variable, is the suggested convention:

foreach (var line in lines) {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top