C# 如何循环来自 TextReader 的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12687453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:06:51  来源:igfitidea点击:

How to loop over lines from a TextReader?

c#.nettextreader

提问by Colonel Panic

How do I loop over lines from a TextReadersource?

如何循环来自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'

foreach 语句无法对“System.IO.TextReader”类型的变量进行操作,因为“System.IO.TextReader”不包含“GetEnumerator”的公共定义

采纳答案by Rawling

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

回答by cuongle

You can use File.ReadLineswhich is deferred executionmethod, then loop thru lines:

您可以使用File.ReadLineswhich 是延迟执行方法,然后通过以下行循环:

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

More information:

更多信息:

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

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

回答by Aghilas Yakoub

You can try with this code - based on ReadLine method

您可以尝试使用此代码 - 基于 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;