Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Stream.Dispose always call Stream.Close (and Stream.Flush)

Tags:

c#

.net

using

If I have the following situation:

StreamWriter MySW = null; try {    Stream MyStream = new FileStream("asdf.txt");    MySW = new StreamWriter(MyStream);    MySW.Write("blah"); } finally {    if (MySW != null)    {       MySW.Flush();       MySW.Close();       MySW.Dispose();    } } 

Can I just call MySW.Dispose() and skip the Close even though it is provided? Are there any Stream implimentations that don't work as expected (Like CryptoStream)?

If not, then is the following just bad code:

using (StreamWriter MySW = new StreamWriter(MyStream)) {    MySW.Write("Blah"); } 
like image 707
JasonRShaver Avatar asked May 26 '09 15:05

JasonRShaver


People also ask

Does Dispose call close?

The StreamWriter method is similar. So, reading the code it is clear that that you can call Close() & Dispose() on streams as often as you like and in any order. It won't change the behaviour in any way.

Does StreamWriter Dispose close the stream?

Close() just calls StreamWriter. Dispose() under the bonnet, so they do exactly the same thing. StreamWriter. Dispose() does close the underlying stream.

How do you Dispose of a stream?

If your stream is using an operating system handle to communicate with its source, consider using a subclass of SafeHandle for this purpose. This method is called by the public Dispose method and the Finalize method. Dispose invokes the protected Dispose method with the disposing parameter set to true .

What is the difference between close and Dispose in VB net?

The main difference between Close and Dispose in the case of SqlConnectionObject is: An application can call Close more than one time. No exception is generated. If you called Dispose method SqlConnection object state will be reset.


2 Answers

Can I just call MySW.Dispose() and skip the Close even though it is provided?

Yes, that’s what it’s for.

Are there any Stream implementations that don't work as expected (Like CryptoStream)?

It is safe to assume that if an object implements IDisposable, it will dispose of itself properly.

If it doesn’t, then that would be a bug.

If not, then is the following just bad code:

No, that code is the recommended way of dealing with objects that implement IDisposable.

More excellent information is in the accepted answer to Close and Dispose - which to call?

like image 122
Binary Worrier Avatar answered Sep 21 '22 03:09

Binary Worrier


I used Reflector and found that System.IO.Stream.Dispose looks like this:

public void Dispose() {     this.Close(); } 
like image 26
Andrew Hare Avatar answered Sep 22 '22 03:09

Andrew Hare