是什么File.ReadLines()和File.ReadAllLines()之间的区别? [英] What is the difference between File.ReadLines() and 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 usingFile.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 anIEnumerable<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()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!