c# - OpenText 与 ReadLines

标签 c# file-io stream readline

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

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

但是我个人会这样做:

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

}

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

最佳答案

客观地:

  • 第一个是一条一条地挑选线,你做这个过程 在流式传输数据时。

  • 第二个生成IEnumerable<string>一次然后你可以 开始处理这些行(来源 MSDN - 我很抱歉混合它 与 ReadAllLines一开始)。

有用吗?

  • 从这个意义上说,第一个更“流畅”。因为你可以选择 随意采取/处理和中断/继续。每次你需要一行,你就拿一条,你处理它,然后你选择中断或继续。您甚至可以选择不再走任何线路(假设您在 yield 循环中有 while),直到您想随意返回
  • 第二个会得到 IEnumerable<string> (也就是说,在处理之前指定预期数据的信息)因此首先会产生一些开销。然而,需要注意的是,这个开销相对较小,因为 IEnumerable推迟实际执行,不像List .一些good inforead .

而来自 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>.

关于c# - OpenText 与 ReadLines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34916237/

相关文章:

ios - 通过流播放的音频出现抖动/断断续续

c# - 得到错误 : "Specified block size is not valid for this algorithm" while initialize AesCryptoProvider

c++ - 将文件数据从服务器返回到客户端 - reg

javascript - 上传前的文件大小和 mime 类型

java - 从 HDFS 下载大文件

php - VB 类流的 PHP 等价物是什么?

c# - 所有 UWP 样本在启动画面卡住

c# - 动态更改 azure 配置 (.cscfg) 值

C# 模拟系统崩溃

java - 可中断套接字读取Java