File.ReadAllLines或Stream Reader

Has*_*san 6 .net c# stream winforms

我们可以通过使用StreamReader或使用来读取文件File.ReadAllLines.

例如,我想将每一行加载到每一行Liststring[]进行进一步操作.

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

foreach(string line in lines)
{
     //DoSomething(line);
}
Run Code Online (Sandbox Code Playgroud)

要么

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 
Run Code Online (Sandbox Code Playgroud)

应用程序遇到不同大小的文本文件.哪个可以从少数增长KBsMBs偶尔.

我的问题是,哪一个是首选方式,为什么一个应该优先于其他方式?

Mat*_*son 15

如果要处理文本文件的每一行而不将整个文件加载到内存中,最好的方法是这样的:

foreach (var line in File.ReadLines("Filename"))
{
    // ...process line.
}
Run Code Online (Sandbox Code Playgroud)

这样可以避免加载整个文件,并使用现有的.Net函数来执行此操作.

但是,如果由于某种原因需要将所有字符串存储在数组中,那么最好只使用File.ReadAllLines()- 但如果您只是foreach用来访问数组中的数据,那么请使用File.ReadLines().

  • @NicholasCarey不,这是不会那样做的版本:`public static IEnumerable <string> ReadLines()`...因此我的评论"没有将整个文件加载到内存中" (5认同)
  • @downvoter:愿意解释一下吗?否决正确答案似乎很奇怪......;) (2认同)

Sam*_*Axe 13

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();
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

逐行读取StreamReader文件,会消耗更少的内存。而一次File.ReadAllLines读取所有行并将其存储到 中,则会消耗更多内存。如果大于的话就会产生内存溢出(32位操作系统的限制)。string[]string[]int.maxvalue

所以,对于更大的文件StreamReader会更有效率。