10

In my app, I'm using a StreamWriter to stream data to a file. Are any bytes actually written to the file before the Close() method is called? If the answer is no, is this true no matter how large the stream is?

Randy

Randy Minder
  • 47,200
  • 49
  • 204
  • 358

3 Answers3

17

The StreamWriter has an internal buffer, and once that buffer is full, it will get flushed to disk. You can force it to flush to disk at any time by calling Flush()

You can specify how big of a buffer you want in the constructors of StreamWriters if you wish.

Matt Greer
  • 60,826
  • 17
  • 123
  • 123
  • 4
    Flush() does not guarantee actual writing to disk - it merely flushes CLR buffers to OS buffers. See [this question](http://stackoverflow.com/questions/383324/how-to-ensure-all-data-has-been-physically-written-to-disk). – bavaza Sep 09 '14 at 13:53
0

Stream is written by StreamWriter.Flush.

Li0liQ
  • 11,158
  • 35
  • 52
  • 5
    I won't downvote, but this isn't entirely correct. Yes, `Flush` will do just that, but that certainly isn't the *only* time that the stream is written before close. See Matt Greer's answer. – Adam Robinson Jan 04 '10 at 19:35
  • 1
    Thats how you can force it to write, but it can also be written by setting AutoFlush() as well as if the internal buffer fills before the flush can be issued. – GrayWizardx Jan 04 '10 at 19:35
0

It depends on the underlying stream that is being used, the size of the buffer in that stream and other factors.

You can force a write to the underlying stream by calling flush() on your StreamWriter.

I assume from your question that you are using a file stream underneath. In my experience the flush generally occurs between every 1-4K of data, but I am not sure what the exact point is.

GrayWizardx
  • 19,561
  • 2
  • 30
  • 43