可能的重复:
C# 逐行读取文件
如何循环遍历 TextReader 中的行?

我得到了.NET 文本阅读器 (可以读取一系列连续字符的类)。如何逐行循环其内容?

有帮助吗?

解决方案

你的意思是这样的吗?

string line = null;
while((line = reader.ReadLine()) != null) 
{
    // do something with line
}

其他提示

您可以非常轻松地创建扩展方法,以便您可以使用 foreach:

public static IEnumerable<string> ReadLines(this TextReader reader)
{
    string line = null;
    while((line = reader.ReadLine()) != null) 
    {
        yield return line;
    }
}

请注意,这 惯于 最后为您关闭阅读器。

然后您可以使用:

foreach (string line in reader.ReadLines())

编辑:正如评论中指出的,这是懒惰的。它一次只会读取一行,而不是将所有行读入内存。

我目前拥有的非惰性解决方案:

foreach(string line in source.ReadToEnd().Split(Environment.NewLine.ToArray(),StringSplitOptions.None))

你会像这样使用它:

string line;
while ((line = myTextReader.ReadLine()) != null)
{
    //do whatever with "line";
}

或者

string Myfile = @"C:\MyDocument.txt";
using(FileStream fs = new FileStream(Myfile, FileMode.Open, FileAccess.Read))
{                    
    using(StreamReader sr = new StreamReader(fs))
    {
        while(!sr.EndOfStream)
        {
            Console.WriteLine(sr.ReadLine());
        }
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top