简体   繁体   中英

How can you disregard the buffer of a streamwriter

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM