【问题标题】:C# I/O - Difference between System.IO.File and StreamWriter/StreamReaderC# I/O - System.IO.File 和 StreamWriter/StreamReader 之间的区别
【发布时间】:2010-10-13 13:57:58
【问题描述】:

假设我只对处理文本文件感兴趣,与 StreamWriter 相比,System.IO.File 方法有哪些具体的优势或劣势?

是否涉及任何性能因素?基本区别是什么,在什么情况下应该使用哪些?

还有一个问题,如果我想将文件的内容读入字符串并在其上运行 LINQ 查询,哪个最好?

【问题讨论】:

  • File 和 StreamWriter/Reader 几乎没有相似。您能否按照 Aliostad 的要求更具体地说明您要比较的File 上的哪些 方法?

标签: c# file-io


【解决方案1】:

File 类中看似重复的方法背后有一段有趣的历史。它是在对 .NET 的预发布版本进行可用性研究之后产生的。他们请一组经验丰富的程序员编写代码来操作文件。他们以前从未接触过 .NET,只是有文档可以工作。成功率为0%。

是的,有区别。当您尝试读取一个千兆字节或更大的文件时,您会发现。这是 32 位版本的保证崩溃。逐行读取的 StreamReader 没有这样的问题,它将使用很少的内存。这取决于程序的其余部分做什么,但尽量将便捷方法限制为不大于几兆字节的文件。

【讨论】:

    【解决方案2】:

    通常我会选择System.IO.File 而不是StreamReader,因为前者主要是后者的方便包装。考虑File.OpenText背后的代码:

    public static StreamReader OpenText(string path)
    {
        if (path == null)
        {
            throw new ArgumentNullException("path");
        }
        return new StreamReader(path);
    }
    

    File.ReadAllLines:

    private static string[] InternalReadAllLines(string path, Encoding encoding)
    {
        List<string> list = new List<string>();
        using (StreamReader reader = new StreamReader(path, encoding))
        {
            string str;
            while ((str = reader.ReadLine()) != null)
            {
                list.Add(str);
            }
        }
        return list.ToArray();
    }
    

    您可以使用 Reflector 来查看其他一些方法,您可以看到它非常简单

    要读取文件的内容,请看:

    【讨论】:

      【解决方案3】:

      你的意思是什么方法?

      WriteAllLines()WriteAllText 例如在幕后使用 StreamWriter。 这是反射器的输出:

      public static void WriteAllLines(string path, string[] contents, Encoding encoding)
      {
      if (contents == null)
          {
              throw new ArgumentNullException("contents");
          }
          using (StreamWriter writer = new StreamWriter(path, false, encoding))
          {
              foreach (string str in contents)
              {
                  writer.WriteLine(str);
              }
          }
      }
      
      
      public static void WriteAllText(string path, string contents, Encoding encoding)
      {
          using (StreamWriter writer = new StreamWriter(path, false, encoding))
          {
              writer.Write(contents);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-05-17
        • 2012-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-29
        • 1970-01-01
        相关资源
        最近更新 更多