12

How do I loop over lines from a TextReader source?

I tried

foreach (var line in source)

But got the error

foreach statement cannot operate on variables of type 'System.IO.TextReader' because 'System.IO.TextReader' does not contain a public definition for 'GetEnumerator'

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465

3 Answers3

45
string line;
while ((line = myTextReader.ReadLine()) != null)
{
    DoSomethingWith(line);
}
Rawling
  • 49,248
  • 7
  • 89
  • 127
  • 4
    Very helpful. First time seeing assignment and check at the same time in a loop like this; I wouldn't have thought of doing it this way. – Denis M. Kitchen Nov 29 '12 at 17:25
17

You can use File.ReadLines which is deferred execution method, then loop thru lines:

foreach (var line in File.ReadLines("test.txt"))
{
}

More information:

http://msdn.microsoft.com/en-us/library/dd383503.aspx

cuongle
  • 74,024
  • 28
  • 151
  • 206
3

You can try with this code - based on ReadLine method

        string line = null;
        System.IO.TextReader readFile = new StreamReader("...."); //Adjust your path
        while (true)
        {
            line = readFile.ReadLine();
            if (line == null)
            {
                break;    
            }
            MessageBox.Show (line);
        }
        readFile.Close();
        readFile = null;
Michael Coxon
  • 5,311
  • 1
  • 24
  • 51
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51