3

I always use streamwriter writer = new StreamWriter(file) to write to file. The problem is it wont actually write to file until writer.close().

If between class create and class close something bad happens (and the program never reaches writer close), I wont get any information in the file. How to force write between create and close?

JensG
  • 13,148
  • 4
  • 45
  • 55
John Ryann
  • 2,283
  • 11
  • 43
  • 60
  • I also want help with this. The solutions below do not help me, as I want to pull content from the file as the program is still running and actively writing to the file. – Xonatron Dec 08 '18 at 20:31

2 Answers2

9

Make sure you have your code wrapped in a using statement:

using (var writer = new StreamWriter(file))
{
    // do your writing
}

This will help "clean up" by disposing (and flushing and closing) the stream for you, such as in situations where Close() would not get called if an unhandled exception were to be thrown after instantiation of the stream. The above is basically equivalent to:

{
    var writer = new StreamWriter(file);
    try
    {
        // do your writing
    }
    finally
    {
        if (writer != null)
            ((IDisposable)writer).Dispose();
    }
}

Note: anything that implements the IDisposable interface should be used within a using block to make sure that it is properly disposed.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
7

If it's important that any pending writes actually be written out to disk before the writer is closed, you can use Flush.

Having said that, it sounds like your real problem is that you're not closing your writer when you should be, at least under certain circumstances. You should be closing the writer no matter what once you're done writing to it (even in the event of an exception). You can use a using (or an explicit try/finally block, if you want) to ensure that the writer is always closed.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • I was having the same problem as the OP. Using Flush write to the file even if you stop it in the middle of debugging. Thanks! – Justin Nov 02 '16 at 20:29