OpenText 与 ReadLines

OpenText vs ReadLines

我遇到了一个逐行读取文件的实现,如下所示:

using (StreamReader reader = File.OpenText(path))
while (!reader.EndOfStream)
{
    string line = reader.ReadLine();
}

但是我个人会这样做:

foreach (string line in File.ReadLines(path))
{

}

是否有理由选择一个而不是另一个?

客观上:

  • 第一个是一条一条的挑线你做工序 当您流式传输数据时。

  • 第二个一次性生成IEnumerable<string>然后就可以了 开始处理这些行(来源 MSDN - 我很抱歉将其混合 首先是 ReadAllLines)。

有用吗?:

  • 从这个意义上说,第一个更 "fluid"。因为你可以选择 take/process 和 break/continue 随意。每次你需要一行,你就拿一条,你处理它,然后你选择中断或继续。你甚至可以选择不走任何进一步的线路(假设你在 while 循环中有 yield)直到你想随意回来
  • 第二个会得到IEnumerable<string>(即在处理之前指定预期数据的信息),因此一开始会产生一些开销。但是,需要注意的是,与 List 不同,此开销相对较小,因为 IEnumerable 会延迟实际执行。一些 good info to read.

而来自 MSDN 以下是 ReadLines 的用例:

Perform LINQ to Objects queries on a file to obtain a filtered set of its lines.

Write the returned collection of lines to a file with the File.WriteAllLines(String, IEnumerable<String>) method, or append them to an existing file with the

File.AppendAllLines(String, IEnumerable<String>) method. Create an immediately populated instance of a collection that takes an IEnumerable<T> collection of strings for its constructor, such as a IList<T> or a Queue<T>.

方法一

比方法 2 更冗长。所以有更多的机会被塞满。

方法二

更简洁,更直接地封装了意图 - 更容易阅读和遵循,也减少了把事情搞砸的可能性(比如忘记处理 reader 等)。