FileStream Vs System.IO.File.WriteAllText when writing to files [closed]

FileStream gives you a little more control over writing files, which can be beneficial in certain cases. It also allows you to keep the file handle open and continuously write data without relinquishing control. Some use cases for a stream:

  • Multiple inputs
  • Real time data from a memory/network stream.

System.IO.File contains wrappers around file operations for basic actions such as saving a file, reading a file to lines, etc. It’s simply an abstraction over FileStream.

From the .NET source code here is what WriteAllText does internally:

private static void InternalWriteAllText(string path,
    string contents, Encoding encoding)
{
    Contract.Requires(path != null);
    Contract.Requires(encoding != null);
    Contract.Requires(path.Length > 0);
    using (StreamWriter sw = new StreamWriter(path, false, encoding))
        sw.Write(contents);
}

Leave a Comment