假设我只对处理文本文件感兴趣,与 StreamWriter 相比,System.IO.File 方法有哪些具体的优点或缺点?
是否涉及任何性能因素?基本区别是什么?在什么情况下应该使用其中哪一个?
还有一个问题,如果我想将文件的内容读入字符串并对其运行 LINQ 查询,哪个最好?
File 类中看似重复的方法背后有一些有趣的历史。它是在对 .NET 预发行版本进行可用性研究后产生的。他们要求一群经验丰富的程序员编写代码来操作文件。他们以前从未接触过 .NET,只是有文档可供参考。成功率为0%。
是的,有区别。当您尝试读取千兆字节或更大的文件时,您就会发现这一点。这在 32 位版本上肯定会崩溃。逐行读取的 StreamReader 不存在这样的问题,它将使用很少的内存。这取决于程序的其余部分的功能,但尝试将便捷方法限制为不大于十几兆字节的文件。
一般来说,我会选择
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 来查看其他一些方法,您可以看到它非常简单
要阅读文件内容,请查看:
您指的是哪种方法?
例如,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);
}
}