4

I'm using a 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, till the close is called no data is written to the file.

Is there any way i can save the contents to the file before closing.

1
  • 2
    Just a hint : you should use the using statement for your streamwriter.
    – thomasb
    Jun 1, 2015 at 7:48

4 Answers 4

5

For this purpose you can use 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

5

I think you are looking for Flush.

file.Flush();

should do the trick.

4

Call Flush() to force buffers to be written:

file.Flush();

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

Or set AutoFlush property

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.

2

Cycle:

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.