net – Using and picture in MemoryStream

Question:

Why does this code work

Dim PctStream As MemoryStream = Await GetSomePct()
Me.BackgroundImage = Bitmap.FromStream(PctStream)

and this one – no?

Using PctStream As MemoryStream = Await GetSomePct()
  Me.BackgroundImage = Bitmap.FromStream(PctStream)
End Using

In the case of Using , a crossed-out rectangle is displayed instead of a picture.

Answer:

The problem is that you are closing the stream that GDI + accesses when rendering.

There is a note on MSDN :

It is necessary to keep the stream open for the lifetime of the Image

Scroll to Top