vb.netstreamreader

checking on whether a streamreader is open gives a warning in VB.net


This scheme

        Try
        SR= New StreamReader(...)
    Catch ex As Exception
        MsgBox(ex.Message, vbOK, "Error opening File")
        GoTo wrapup
    End Try  
... {do things}
    wrapup:
        SR.Dispose()
        If SR IsNot Nothing Then SR.Close()
        If SR.BaseStream IsNot Nothing Then SR.Close()

Any of the three ways of closing the Streamreader-SR gives a warning that SR is used before assignment. Is there a proper way to close something you're not sure is open?


Solution

  • StreamReader implements IDisposable. As such, the cleanest way is to use the Using statement, which will ensure proper closing and disposal when the object goes out of scope.

        Using SR As New StreamReader(...)
    
            ... {do things}
    
        End Using
    

    In addition, I recommend you cease using "VB6-compaitble" code, such as MsgBox, and move to current VB.NET constructs such as MessageBox.

    I'll hold my tongue on GoTo :-)