How to loop over lines from a TextReader?
Asked Answered
I

3

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'

Incommunicado answered 2/10, 2012 at 9:8 Comment(2)
#287033Merylmes
Or even #1271725 too.Gratin
Z
45
string line;
while ((line = myTextReader.ReadLine()) != null)
{
    DoSomethingWith(line);
}
Z answered 2/10, 2012 at 9:13 Comment(1)
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.Helga
O
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

Olenta answered 2/10, 2012 at 9:10 Comment(0)
M
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;
Marhtamari answered 2/10, 2012 at 9:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.