我有一个关于查询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()之间的区别?
发布评论