File.ReadAllLines或StreamReader?

24
我们可以使用 StreamReader 或者 File.ReadAllLines 来读取文件。
例如,我想将每一行加载到一个 Liststring[] 中,以便进一步操作每一行。
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<string>
    }
}

//if list is created loop through list here 

应用程序会遇到大小不同的文本文件,这些文件的大小可能从几个 KB 到偶尔的 MBs

我的问题是哪种方法更受欢迎,为什么应该优先考虑一种而不是另一种?


3
以下是需要翻译的内容:https://dev59.com/Dmsz5IYBdhLWcg3wOlSh请问读取文本文件逐行的最快方法是什么? - Yuval Itzchakov
首选用于什么目的?速度、内存还是其他? - Steve
@YuvalItzchakov 谢谢,我正在查看链接。 - Hassan
@Steve,速度和内存都很重要。如果出现更大的文本文件,则应用程序应有效地读取所有行。 - Hassan
那么上面的链接应该能够给你一个完整的答案。 - Steve
3个回答

41

如果你想处理文本文件中的每一行而不将整个文件加载到内存中,则最好的方法如下:

foreach (var line in File.ReadLines("Filename"))
{
    // ...process line.
}

这样可以避免加载整个文件,并使用现有的 .Net 函数来实现。

然而,如果您由于某种原因需要将所有字符串存储在数组中,则最好直接使用 File.ReadAllLines() - 但如果您只是使用 foreach 来访问数组中的数据,则使用 File.ReadLines() 更为适合。


2
@downvoter:能解释一下吗?似乎很奇怪会对正确的答案进行负评... ;) - Matthew Watson
可能被踩是因为File.ReadLines()将整个文件读入内存(一个string[])。 - Nicholas Carey
8
不,这是不会加载整个文件到内存中的版本:public static IEnumerable<string> ReadLines()... 因此我的评论是“不需要将整个文件加载到内存中”。 - Matthew Watson
1
@MatthewWatson 我同意你的观点,虽然这是一个老话题 - 为了那些将要阅读并感到困惑的人而投了一票。 - TripleEEE

25

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<String> lines = new List<String>();

        using (StreamReader sr = new StreamReader(path, encoding))
            while ((line = sr.ReadLine()) != null)
                lines.Add(line);

        return lines.ToArray();
    }

5
StreamReader逐行读取文件,它会消耗更少的内存。然而,File.ReadAllLines 一次性读取所有行,并将其存储到string[]中,这会消耗更多内存。如果那个 string[] 大于int.maxvalue,那么会产生内存溢出(在32位操作系统上有限制)。
因此,对于较大的文件,StreamReader 将更加高效。

1
考虑到Sam关于ReadAllLines内部使用StreamReader的回答,这个答案是否无效? - Stuart Dobson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接