开发者

C# I/O - Difference between System.IO.File and StreamWriter/StreamReader

Assuming I am interested only in d开发者_C百科ealing with text files, what specific advantages or disadvantages does System.IO.File methods provide when compared to StreamWriter?

Are there any performance factors involved? What is the basic difference, and which of these should be used in what cases?

One more question, If i want to read the contents of a file into a string and run a LINQ query over it, which is best?


There's a bit of interesting history behind the seemingly duplicate methods in the File class. It came about after a usability study on a pre-release version of .NET. They asked a group of experienced programmers to write code to manipulate files. They were never exposed to .NET before and just had the docs to work from. The success rate was 0%.

Yes, there's a difference. You'll find out when you try to read a file that's a gigabyte or more. That's a guaranteed crash on the 32-bit version. No such problem with a StreamReader that reads line-by-line, it will use very little memory. It depends on what the rest of your program does but try to limit the convenience method to files no larger than, say, a couple of megabytes.


Generally I'd go with System.IO.File over StreamReader as the former is mostly a convenient wrapper for the latter. consider the code behind File.OpenText:

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

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

You can use Reflector to check out some other methods, as you can see it's pretty straightforward

For reading the contents of the file, take a look at:

  • File.ReadAllLines
  • File.ReadAllText


Which method do you mean?

WriteAllLines() and WriteAllText for example uses StreamWriter behind the scene. Here is the reflector output:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜