9

Does the following close the file after the operation is performed? :

System.IO.File.AppendAllText(path, text);

A yes, no will suffice?

Adrian
  • 6,013
  • 10
  • 47
  • 68
JL.
  • 78,954
  • 126
  • 311
  • 459

2 Answers2

16

Yes, it does.

If it didn't, there'd be no way of closing it afterwards as it doesn't return anything to dispose.

From the docs:

Given a string and a file path, this method opens the specified file, appends the string to the end of the file, and then closes the file.

The other utility methods (ReadAllText, WriteAllBytes etc) work the same way.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks I was inclined to use a StreamWriter, but this seems so much easier. – JL. Dec 04 '09 at 10:22
  • It seems to be a naming convention that all IO methods that contain `All` dispose/close the underlying streams, f.e.: `File.AppendAllLines`, `File.AppendAllText`, `File.ReadAllBytes`, `File.ReadAllLines`, `File.ReadAllText`, `File.WriteAllLines`, `File.WriteAllText`. It's no guarantee but a good mnemonic. – Tim Schmelter Jul 07 '15 at 07:57
  • @TimSchmelter: I'd go by "Does it return a stream / reader / writer?" If not, it should be closing everything (as there's nothing else it can do). If it does, it won't be returning you something that's already closed. – Jon Skeet Jul 07 '15 at 08:06
  • @JonSkeet: yes, another good indication. But then you have to look closer, either at documentation or in visual studio. The naming convention helps to clarify things beforehand. There are also methods where it's not obvious from the return type if it closes the stream like `File.ReadLines` as opposed to `ReadAllLines`. – Tim Schmelter Jul 07 '15 at 08:16
4

This is the code of the method:

public static void AppendAllText(string path, string contents, Encoding encoding)
{
    using (StreamWriter writer = new StreamWriter(path, true, encoding))
    {
        writer.Write(contents);
    }
}

Therefore, yes.

Marat Faskhiev
  • 1,282
  • 6
  • 17
  • 37
  • 3
    I don't think it's a good idea to rely on the implementation details unless you absolutely have to. Implementations can change. Fortunately in this case it's explicitly documented. – Jon Skeet Dec 04 '09 at 10:23