C#I / O – System.IO.File和StreamWriter / StreamReader之间的区别

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

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

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

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

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

通常我会在StreamReader使用System.IO.File ,因为前者主要是后者的方便包装器。 考虑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 list = new List(); using (StreamReader reader = new StreamReader(path, encoding)) { string str; while ((str = reader.ReadLine()) != null) { list.Add(str); } } return list.ToArray(); } 

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

要阅读文件内容,请查看:

  • File.ReadAllLines
  • File.ReadAllText

你是说哪种方法?

WriteAllLines()WriteAllText在场景后面使用StreamWriter 。 这是reflection器输出:

 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); } }