Leave input stream open

StewartBW 1,700 Reputation points
2025-06-07T09:08:18.6533333+00:00

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
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,191 Reputation points
    2025-06-07T10:44:37.9066667+00:00

    In your code, only MyImage is disposed

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. 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 the Using block because:

    1. Image.FromStream Parameters:
      • False, False explicitly tells the method:
        • Do not close the stream (leaveOpen: False).
        • Do not validate image data (validateImageData: False).
      • Documentation: Microsoft Docs - Image.FromStream.
    2. Behavior of Using Block:
      • Only MyImage is disposed when the block ends.
      • The InputStream is unaffected and stays open for further use.

    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()
    
    


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.