是什么File.ReadLines()和File.ReadAllLines()之间的区别?

编程入门 行业动态 更新时间:2024-10-09 16:29:24
本文介绍了是什么File.ReadLines()和File.ReadAllLines()之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个关于查询File.ReadLines()和File.ReadAllLines()是两者之间的区别。我有文本文件,其中包含逐行的数据。 File.ReadAllLines()返回的数组,并使用 File.ReadLines()。ToArray的() ; 还将我可以得到同样的result.So有涉及这些方法的任何性能差异

字符串[] =行File.ReadLines。(C:\\mytxt.txt)ToArray的();

的String [] =行File.ReadAllLines(C:\\mytxt.txt);

解决方案

有什么表现区别与这些方法呢?

是是有区别的。

File.ReadAllLines()方法读取一次整个文件并返回String []数组,所以它需要的时间与大尺寸的工作时推荐用户文件,而不是必须等待,直到返回整个数组。

File.ReadLines()收益一个的IEnumerable<字符串方式> ,并没有阅读一气呵成整个文件,因此它是真正与大尺寸文件时,一个更好的选择。

方法不同的readlines方法和ReadAllLines如下:

当您使用readlines方法,你就可以开始列举返回整个集合之前的字符串的集合;当您使用ReadAllLines,您必须等字符串全阵列退回,然后才能访问$ B $数组b。因此,当您正在使用非常大的文件时, readlines方法可以更有效地

例1: File.ReadAllLines()

的String [] =行File.ReadAllLines(C :\\mytxt.txt);

例2: File.ReadLines()

的foreach(在File.ReadLines VAR线(C:\\mytxt.txt)) { //做些什么 }

I have query regarding File.ReadLines() and File.ReadAllLines().what is difference between them. i have text file where it contains data in row-wise.File.ReadAllLines() return array and using File.ReadLines().ToArray(); will also i can get same result.So is there any performance difference related to these methods?

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

Or

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

解决方案

is there any performance difference related to these methods?

YES there is a difference

File.ReadAllLines() method reads the whole file at a time and returns the string[] array, so it takes time while working with large size of files and not recommended as user has to wait untill the whole array is returned.

File.ReadLines() returns an IEnumerable<string> and it does not read the whole file at one go, so it is really a better option when working with large size files.

From 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.

Example 1: File.ReadAllLines()

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

Example 2: File.ReadLines()

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

更多推荐

是什么File.ReadLines()和File.ReadAllLines()之间的区别?

本文发布于:2023-11-03 23:53:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556415.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   File   ReadLines   ReadAllLines

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!