Image.Save(..) throws a GDI+ exception because the memory stream is closed

As it’s a MemoryStream, you really don’t need to close the stream – nothing bad will happen if you don’t, although obviously it’s good practice to dispose anything that’s disposable anyway. (See this question for more on this.)

However, you should be disposing the Bitmap – and that will close the stream for you. Basically once you give the Bitmap constructor a stream, it “owns” the stream and you shouldn’t close it. As the docs for that constructor say:

You must keep the stream open for the
lifetime of the Bitmap.

I can’t find any docs promising to close the stream when you dispose the bitmap, but you should be able to verify that fairly easily.

Leave a Comment