File.ReadAllLines或Stream Reader
我们可以使用StreamReader
或使用File.ReadAllLines
来读取文件。
例如,我想将每一行加载到List
或string[]
以便在每一行上进一步操作。
string[] lines = File.ReadAllLines(@"C:\\file.txt"); foreach(string line in lines) { //DoSomething(line); }
要么
using (StreamReader reader = new StreamReader("file.txt")) { string line; while ((line = reader.ReadLine()) != null) { //DoSomething(line); or //save line into List } } //if list is created loop through list here
应用程序遇到不同大小的文本文件。 偶尔可以从几KBs
到MBs
增长。
我的问题是哪一个是首选方式,为什么一个应该优先于其他方式?
如果要处理文本文件的每一行而不将整个文件加载到内存中,最好的方法是这样的:
foreach (var line in File.ReadLines("Filename")) { // ...process line. }
这样可以避免加载整个文件,并使用现有的.Net函数来完成。
但是,如果由于某种原因需要将所有字符串存储在数组中,那么最好只使用File.ReadAllLines()
– 但如果您只使用foreach
来访问数组中的数据,那么请使用File.ReadLines()
。
Microsoft在File.ReadAllLines中使用StreamReader:
private static String[] InternalReadAllLines(String path, Encoding encoding) { Contract.Requires(path != null); Contract.Requires(encoding != null); Contract.Requires(path.Length != 0); String line; List lines = new List (); using (StreamReader sr = new StreamReader(path, encoding)) while ((line = sr.ReadLine()) != null) lines.Add(line); return lines.ToArray(); }
StreamReader逐行读取文件,它将消耗更少的内存。 而File.ReadAllLines一次读取所有行并将其存储到string []中,它将消耗更多内存。 如果该字符串[]大于int.maxvalue则会产生内存溢出(限制为32位操作系统)。
因此,对于更大的文件,StreamReader将更高效。