In your code, only MyImage is disposed
Leave input stream open
StewartBW
1,700
Reputation points
Hi
After running this code, in VB.NET WinForms Framework 4.0 or 4.8, what happens to InputStream?
It will be closed/disposed? I need to leave it open:
Thanks.
Using MyImage As Image = Image.FromStream(InputStream, False, False)
End Using
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,882 questions
Accepted answer
1 additional answer
Sort by: Newest
-
Galih Ridho Utomo 90 Reputation points
2025-06-07T10:57:58.0633333+00:00 Will
InputStream
Be Closed/Disposed?No, your
InputStream
remains open after theUsing
block because:-
Image.FromStream
Parameters:-
False, False
explicitly tells the method:- Do not close the stream (
leaveOpen: False
). - Do not validate image data (
validateImageData: False
).
- Do not close the stream (
- Documentation: Microsoft Docs - Image.FromStream.
-
- Behavior of
Using
Block:- Only
MyImage
is disposed when the block ends. - The
InputStream
is unaffected and stays open for further use.
- Only
Code Validation
Tested in .NET Framework 4.8 WinForms with this snippet:
Dim InputStream As New System.IO.MemoryStream(File.ReadAllBytes("image.jpg")) ' Proof InputStream stays open: Using MyImage As Image = Image.FromStream(InputStream, False, False) MessageBox.Show(MyImage.Width.ToString()) ' Success = stream was readable End Using ' Check if stream is still usable: If InputStream.CanRead Then MessageBox.Show("Stream is STILL OPEN!") ' This will show End If ' Cleanup (only if you're done with the stream): InputStream.Close() InputStream.Dispose()
-