0

I am using a streamwriter to write to a file stream like so

using(StreamWriter writer = File.AppendText('MyFile.csv'))
{
    writer.WriteLine("Header1,Header2")

    //Write multiple lines based on some logic
    DoSomeOtherThings(writer)

    writer.Flush();
}

If my application errors in the middle of writing, I do not want to write to the file at all. To do this I thought I would just not have to flush until the end. However even if there is an error any data that was writing is saved to my file.

Is there a way to disregard the buffer of the StreamWriter so It does not save the data to the file unless it reaches the end of the logic?

user2945722
  • 1,293
  • 1
  • 16
  • 35
  • Clearly you've destroyed the file no matter what you do so you'll need to delete it. Or not append it. Or use a StringWriter instead. – Hans Passant Mar 17 '16 at 16:22
  • Have DoSomeOtherThings write to a memory buffer and if it doesn't fail then write that memory buffer to the file. – Quintium Mar 17 '16 at 16:22
  • Would wrapping the logic in a try catch and closing the base stream (the file stream in this case) in the catch section be a reasonable option? This would close the stream before the writer has a chance to flush the data – user2945722 Mar 17 '16 at 16:36

2 Answers2

0

Flush gets called in the Dispose method of the StreamWriter. See Does Stream.Dispose always call Stream.Close (and Stream.Flush) for instance. And Dispose gets called even if an error has occurred when using the 'using' construct.

Community
  • 1
  • 1
C. Knight
  • 739
  • 2
  • 5
  • 20
  • Does it also get called in the finalizer when it is garbage collected? If not could I simply remove the using statement so it does not get disposed. – user2945722 Mar 17 '16 at 16:46
-1

I haven't tried this but it looks like there is a AutoFlush property on the StreamWriter class. You might be able to set that to false right after you create the writer and it might do what you want.