c# - File.ReadLines() 和 File.ReadAllLines() 有什么区别?

标签 c# readline file.readalllines

<分区>

我有关于 File.ReadLines() 和 File.ReadAllLines() 的问题。两者之间有什么区别 他们。我有文本文件,其中包含按行显示的数据。File.ReadAllLines() 返回数组并使用 File.ReadLines().ToArray(); 我也可以得到相同的结果。那么这些方法是否存在任何性能差异?

string[] lines = File.ReadLines("C:\\mytxt.txt").ToArray();

或者

string[] lines = File.ReadAllLines("C:\\mytxt.txt");

最佳答案

is there any performance difference related to these methods?

有区别

File.ReadAllLines()方法一次读取整个文件并返回 string[] 数组,因此在处理大文件时需要时间并且不推荐,因为用户必须等到整个数组返回。

File.ReadLines()返回 IEnumerable<string>而且它不会一次读取整个文件,因此在处理大文件时确实是一个更好的选择。

来自 MSDN :

The ReadLines and ReadAllLines methods differ as follows:

When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

示例 1:File.ReadAllLines()

string[] lines = File.ReadAllLines("C:\\mytxt.txt");

示例 2:File.ReadLines()

foreach (var line in File.ReadLines("C:\\mytxt.txt"))
{

   //Do something     

}

关于c# - File.ReadLines() 和 File.ReadAllLines() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21969851/

相关文章:

c# - 如何在异步任务 C# 中限制每秒请求

Java - 根据偏移量从随机访问文件中获取行

r - 如何在 R 中等待按键?

c# - 为什么 ReadAllLines 在 WPF 中有效但在 ConsoleApp 中无效

c# - 我如何将 ReadAllLines 与 gzip 文件一起使用

c# - 数组的通用扩展方法无法编译

c# - Servicestack 对象参数未通过 Swagger-UI 传递给服务

c# - 每秒在多个客户端上传输每个套接字数据

java - Readline 和正则表达式匹配出现问题

c# - File.ReadAllLines() 和 File.ReadAllText() 有什么区别?