C # Save Streamwriter after every 200 cycles without closing
I am using StreamWriter to write some data to a file.
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();
What I noticed is that until the close is called, no data is written to the file.
Is there a way to preserve the contents of the file before closing.
+3
source to share
4 answers
For this purpose, you can use the Flush method.
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();
For more information, welcome to MSDN
+3
source to share
Call Flush()
to force buffers to write:
file.Flush();
Clears all buffers for the current author and causes any buffered data to be written to the underlying stream.
Or set the AutoFlush property
file.AutoFlush = true;
Gets or sets a value indicating whether the StreamWriter will flush its buffer into the underlying stream after each call to StreamWriter.Write.
+4
source to share