solomem / C-

0 stars 0 forks source link

System.IO.File vs StreamReader #7

Open solomem opened 1 year ago

solomem commented 1 year ago

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

solomem commented 1 year ago

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