Jez
Jez

Reputation: 30063

Should I close streams returned by Assembly.GetManifestResourceStream?

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?

Upvotes: 10

Views: 2054

Answers (1)

Steve Danner
Steve Danner

Reputation: 22158

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.

Upvotes: 5

Related Questions