[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 477
  • Last Modified:

StreamWriter Opening and Closing

I know how to create a StreamWriter like so:

Dim srFileWriter As New System.IO.StreamWriter("RecResults.txt", True)

close it like this

srFileWriter.Close()


but say I want to reopen that file for more writing after I close it. How do I do that with the same object? You see two functions trade off writing to this file...so I have to close one stream to allow the other to do some writing..then reopen it when the function returns.
0
SGyves
Asked:
SGyves
2 Solutions
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Don't close the StreamWriter.  Instead either pass the StreamWriter instance to your functions so you can use the same instance or declare it at a higher level (Form or Global) so it can be accessed from both places.
0
 
PockyMasterCommented:
You might consider writing a disposable class for it.

Imports System.IO

Public Class CFileWriter
    Implements IDisposable

    Private disposedValue As Boolean = False        ' To detect redundant calls
    Private _srFile As StreamWriter

    Public Sub New(ByVal sFileName As String, ByVal append As Boolean)
        _srFile = New StreamWriter(sFileName, append)
    End Sub

    Public Sub Write(ByVal sText As String)
        _srFile.Write(sText)
    End Sub

    Public Sub WriteLine(ByVal sText As String)
        _srFile.WriteLine(sText)
    End Sub

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                If Not _srFile Is Nothing Then _srFile.Dispose()
            End If
        End If
        Me.disposedValue = True
    End Sub

#Region " IDisposable Support "
    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class
0
 
SGyvesAuthor Commented:
I will probably just go for simplicity for now and learn about the IDispose black magic later.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now