How to loop over lines from a TextReader?

最后都变了- 提交于 2019-11-30 23:20:41

问题


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'


回答1:


string line;
while ((line = myTextReader.ReadLine()) != null)
{
    DoSomethingWith(line);
}



回答2:


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




回答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;


来源:https://stackoverflow.com/questions/12687453/how-to-loop-over-lines-from-a-textreader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!