c# 在每 200 个循环后保存 Streamwriter 而不关闭

c# Save Streamwriter after every 200 Cycles without Closing

我正在使用 StreamWriter 将一些数据写入文件。

System.IO.StreamWriter file = new System.IO.StreamWriter(path);
while(something_is_happening && my_flag_is_true)
     file.WriteLine(some_text_goes_Inside);

file.close();

我注意到,在调用关闭之前,没有数据写入文件。

有什么方法可以在关闭前将内容保存到文件中。

调用Flush()强制写入缓冲区:

file.Flush();

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

或设置AutoFlush属性

file.AutoFlush = true;

Gets or sets a value indicating whether the StreamWriter will flush its buffer to the underlying stream after every call to StreamWriter.Write.

我想你正在寻找 Flush

file.Flush();

应该可以解决问题。

周期:

System.IO.StreamWriter file = new System.IO.StreamWriter(path);
for (int i = 0; true && flag; i++)
{
    file.WriteLine(some_text_goes_Inside);
    if (i == 200)
    {
        file.Flush();
        i = 0;
    }
}
file.Close();

为此,您可以使用 Flush 方法。

System.IO.StreamWriter file = new System.IO.StreamWriter(path);
int counter = 0;
while(something_is_happening && my_flag_is_true)
{
    file.WriteLine(some_text_goes_Inside);
    counter++;
    if(counter < 200) continue;
    file.Flush();
    counter = 0;
}
file.Close();

更多信息欢迎访问MSDN