Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I close streams returned by Assembly.GetManifestResourceStream?

Tags:

c#

stream

I had thought that it was good practice, when accessing embedded assembly resources using the Assembly.GetManifestResourceStream method, to close the returned Stream after finishing with it. However, I just spotted something in the following article:

http://msdn.microsoft.com/en-us/library/ms950960.aspx

// Get the stream that holds the resource
// NOTE1: Make sure not to close this stream!
// NOTE2: Also be very careful to match the case
//        on the resource name itself
Stream stream =
  assem.GetManifestResourceStream("Azul.jpg");

// Load the bitmap from the stream
this.BackgroundImage = new Bitmap(stream);

The comment here says that the stream should not be closed, though the article makes no mention of why. Searches on Google have provided nothing conclusive; some people seem to close this stream, others don't and say the garbage collector will deal with it.

Should I close streams returned by Assembly.GetManifestResourceStream? Is there a particular reason I shouldn't?

like image 750
Jez Avatar asked Aug 10 '12 17:08

Jez


1 Answers

That comment doesn't want you to close it because it goes on to create a Bitmap object from it. Generally, you should close the streams once you're done using them or your application will be subject to memory leaks.

like image 188
Steve Danner Avatar answered Sep 30 '22 03:09

Steve Danner