Question

I have a class in which I have declared a FileStream and a StreamReader:

Option Strict Off Option Explicit On

Friend Class clsFileReader

    Private _fs As IO.FileStream
    Private _sr As IO.StreamReader

I would like ask if I explicitely need to close these like this:

Protected Overrides Sub Finalize()

    _fs.Close()
    _sr.Close()

End Sub

... or if that is done automatically.

Thank you for the help!

ps: I can not use "using" because I want to read the file line by line like this:

Public Function ReadLine() As String
    Debug.Assert(Not _sr.EndOfStream)

    _sCurrentLineString = _sr.ReadLine

    _iCurentLineIndex = _iCurentLineIndex + 1

    Return _sCurrentLineString

End Function
Was it helpful?

Solution

I would suggest you use the same fonctionality as found in the stream. Implement the IDisposable interface and call .Dispose on your class instance when you're done with it. Same as you would do with a stream.

Here's a quick example.

Class clsFileReader : Implements IDisposable

   Private _fs As IO.FileStream
   Private _sr As IO.StreamReader

   ' Flag: Has Dispose already been called? 
   Dim disposed As Boolean = False 

   ' Public implementation of Dispose pattern callable by consumers. 
   Public Sub Dispose() _
              Implements IDisposable.Dispose
      Dispose(True)
      GC.SuppressFinalize(Me)           
   End Sub 

   ' Protected implementation of Dispose pattern. 
   Protected Overridable Sub Dispose(disposing As Boolean)
      If disposed Then Return 

      If disposing Then 
         ' Free any other managed objects here. 
         ' 
         _fs.Close()
         _sr.Close()
      End If 

      ' Free any unmanaged objects here. 
      '
      disposed = True 
   End Sub 

   Protected Overrides Sub Finalize()
      Dispose(False)      
   End Sub 

End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top