简体   繁体   English

如何忽略流作家的缓冲区

[英]How can you disregard the buffer of a streamwriter

I am using a streamwriter to write to a file stream like so 我正在使用streamwriter写入文件流,像这样

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? 有没有一种方法可以忽略StreamWriter的缓冲区,因此除非到达逻辑末尾,否则它不会将数据保存到文件中?

Flush gets called in the Dispose method of the StreamWriter. 在StreamWriter的Dispose方法中调用Flush。 See Does Stream.Dispose always call Stream.Close (and Stream.Flush) for instance. 例如,请参阅是否Stream.Dispose始终调用Stream.Close(和Stream.Flush) And Dispose gets called even if an error has occurred when using the 'using' construct. 即使使用“ using”构造时发生错误,也会调用Dispose。

I haven't tried this but it looks like there is a AutoFlush property on the StreamWriter class. 我没有尝试过,但看起来StreamWriter类上有一个AutoFlush属性。 You might be able to set that to false right after you create the writer and it might do what you want. 创建编写器后,您可能可以立即将其设置为false,并且它可以执行您想要的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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