2

Looking at 'System.IO.File.AppendAllText' code from the GAC it calls another method called 'InternalAppendAllText' which creates a new StreamWriter and writes the content to the file.

//mscorlib, System.IO
private static void InternalAppendAllText(string path, string contents, Encoding encoding)
{
    using (StreamWriter writer = new StreamWriter(path, true, encoding))
    {
      writer.Write(contents);
    }
}

My question is if I did a for loop calling System.IO.AppentAllText 5 times for example will the StreamWriter be created 5 times, each iteration it is initialized and disposed or it is only initialized once?

Example:

for(int i = 1; i < 4; ++i)
{
    System.IO.File.AppendAllText("a", "a");
}
5
  • Code please. How would you create them? Please post the loop code. Commented Nov 25, 2012 at 20:52
  • @TimSchmelter: Yes it is. It's entirely reasonable to create a file called a. (It doesn't need to be an absolute filename.) Commented Nov 25, 2012 at 20:56
  • On another note, your for loop with the ++i trick is a good way of making off-by-one mistakes, especially if your code will be used by others. It's an extremely convoluted and unclear way of looping 5 times. Commented Nov 25, 2012 at 21:03
  • @AvnerShahar-Kashtan - "your for loop with the ++i trick is ... an extremely convoluted and unclear way of looping 5 times" - in this case ++i and i++ are exactly equivalent, both will loop 3 times, not 5. Commented Nov 25, 2012 at 21:50
  • @Joe Point proven, then. I had assumed the convoluted syntax will achieve the stated objective and didn't bother unravelling it in my head. :) Commented Nov 26, 2012 at 5:54

2 Answers 2

6

The using block is expanded to the equivalent of this code:

StreamWriter writer;
try
{
    writer = new StreamWriter(path, true, encoding))
    writer.Write(contents);
}
finally
{
    if (writer != null)
         writer.Dispose();
}

So yes, whenever a using block exits, the objects are disposed. Whenever you reenter the function, a new StreamWriter will be initialized.

Note, however, that this doesn't have anything to do with the Garbage Collector. The GC will run when it feels like it, scan the allocated objects, notice that there are five StreamWriter objects that aren't attached to any GC Root, and discard them. This is true whether or not you called Dispose or used using, it's just how the GC works.

What using does here is release the unmanaged resource that the object holds - in this case, the file handle. If the StreamWriter was not destroyed or otherwise explicitly closed, the file would have remained locked for editing until your process has finished or the GC decided to activate. This is what using blocks and the IDisposable interace are for - to make sure you explicitly release the objects that the GC doesn't know about.

Sign up to request clarification or add additional context in comments.

Comments

3

If you look at the decompiled code the Stream is in a using statement so it will be cleaned up. It will be initialized all 5 times but it will be cleaned up as soon as the code leaves the using statement.

3 Comments

... and therefore, you should append the text in-memory (StringBuilder!) and interact with the actual file only once per big operation.
Nevertheless the implicit Dispose-call when the using-block is left does not automatically force the garbage collector to come into play. It frees resources kept (and prevents the garbace collector from finalizing the instance first) but the garbage collector will collect the five instances during the next regular cycle.
Nathan, I was answering how the code behaved, not how it should be used , for one because I posted my answer before the question was edited to include code samples and because a blanket statement of how the code should be used would require more that the data that is provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.