tags:

views:

100

answers:

3

Assuming I am interested only in dealing 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?

A: 

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);
    }
}
Aliostad
+2  A: 

Generally I'd go with 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:

ohadsc
+2  A: 

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.

Hans Passant