11

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
  • 126,394
  • 80
  • 383
  • 450

3 Answers3

41
string line;
while ((line = myTextReader.ReadLine()) != null)
{
    DoSomethingWith(line);
}
Rawling
  • 47,604
  • 7
  • 83
  • 119
  • 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
18

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
  • 71,850
  • 28
  • 140
  • 203
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,025
  • 1
  • 23
  • 49
Aghilas Yakoub
  • 27,871
  • 5
  • 44
  • 49