Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need to call Flush() on a stream or writer if you are using the “using” statement?

I am not sure whether I need to call Flush() on the used objects if I write something like this:

using (FileStream...) using (CryptoStream...) using (BinaryWriter...) {     // do something } 

Are they always automatically flushed? When does the using statement flush them and when it doesn’t (if that can happen)?

like image 896
Ben Avatar asked Oct 10 '11 09:10

Ben


People also ask

Does try with resources flush?

The resources are automatically closed when using try-with-resource block. As part of this process it will also invoke flush automatically.

What does stream flush Do C#?

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

Do I need to flush MemoryStream?

You don't need to use Flush on the MemoryStream , as it's not buffering anything that is written to any other source. There is simply nothing to flush anywhere. The Flush method is only present in the MemoryStream object because it inherits from the Stream class.


1 Answers

As soon as you leave the using block’s scope, the stream is closed and disposed. The Close() calls the Flush(), so you should not need to call it manually.

like image 72
Davide Piras Avatar answered Sep 28 '22 12:09

Davide Piras