How to loop over lines from a TextReader?

2019-02-16 11:50发布

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'

3条回答
做自己的国王
2楼-- · 2019-02-16 12:08

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

查看更多
可以哭但决不认输i
3楼-- · 2019-02-16 12:23
string line;
while ((line = myTextReader.ReadLine()) != null)
{
    DoSomethingWith(line);
}
查看更多
做自己的国王
4楼-- · 2019-02-16 12:28

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;
查看更多
登录 后发表回答