Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.CreateText / File.AppendText vs. File.AppendAllText

Tags:

c#

.net

file

In order to use File.CreateText() and File.AppendText() you have to:

  1. open a stream by calling either of those methods
  2. write the message
  3. close the stream
  4. dispose the stream

In order to use File.AppendAllText() you just use it and it will also creates the file if it does not exists yet.

I`m talking about .Net 3.5

Was there any reason to do it like the first above method back then?

like image 874
shahar eldad Avatar asked Jul 25 '26 15:07

shahar eldad


1 Answers

When we look at the implementation of File.AppendAllText we find that it is a shortcut, implemented like this:

using (StreamWriter sw = new StreamWriter(path, true, encoding))
    sw.Write(contents);

The other methods open a stream and return it, and it is up to the caller to write to it, pass it on, etc.

It is always difficult to ask for the reason behind such a design decision. In this case it seems obvious: The "All" infix suggests that the caller would have a complete string that should be written at once, and there is no need to keep the stream open - it has been added for convenience, because that is a frequent use case.

To back this up, I have found this quote from Petzold:

However, in .NET 2.0 some additional static methods were added to the File class that make a whole lot of sense. These methods let you open, read from (or write to), and close a file, all in one statement.

Completely removing the previous methods in favor of the simplified ones would mean a loss in flexibility - developers will still have cases where working with a stream is required.

like image 160
Cee McSharpface Avatar answered Jul 27 '26 06:07

Cee McSharpface



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!