C# I/O - System.IO.File和StreamWriter/StreamReader的区别

14

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

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

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


文件和StreamWriter/Reader几乎没有类似之处。您能否更具体地说明,正如Aliostad所要求的那样,并指定您正在比较哪些File方法? - Kirk Woll
3个回答

16
在File类中,看似重复的方法背后有一段有趣的历史。这是在.NET的预发布版本上进行可用性研究后产生的。他们请一组经验丰富的程序员编写代码来操作文件。他们以前从未接触过.NET,只能依靠文档进行工作。成功率为0%。
是的,确实有区别。当您尝试读取一个占用1GB或更多空间的文件时,您会发现其中的差异。在32位版本上,这将导致崩溃。而使用逐行读取的StreamReader则不会出现这个问题,它将占用非常少的内存。这取决于您的程序的其他部分,但请尽量将方便的方法限制在大小不超过几十兆字节的文件上。

您能提供可用性研究的来源吗? - Alexander Summers
1
https://www.youtube.com/watch?v=3lZP2j9bjbU - Hans Passant

5
通常情况下,我会选择使用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);
    }
}

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