VB.NET How to Keep a file open for writing

203 views Asked by At

trying to convert a VB6 program just now, it uses FILESYSTEMOBJECT to create a TEXTSTREAM for appending, and once opened it is kept open for the whole process as this is the method of writing to the LOG files. The recommended method seems to be SYSTEM.IO for a replacement.

All the info I can find (FILES and STREAMWRITER) all seem to Open / Write / Close, the file every time we want to append to it. We are looking to keep the file open and the stream active to remove any overheads in the OPEN / CLOSE for each write. New to VB.NET so any pointers are greatly appreciated.

One constraint we have is that we can't build up multiple lines of text and then write them all at once, the business need it written to after each action

I have experimented with USING - END USING for TEXTSTREAMS and FILE.CREATE / APPENDALLText

2

There are 2 answers

1
Idle_Mind On BEST ANSWER

You can definitely use a StreamWriter. Just don't close it until you're ready to.

If you need to access it from multiple methods, then declare it class/form level and it'll stay open for the lifetime of the app, or until you explicitly close it:

Imports System.IO
Public Class Form1

    Private sw As StreamWriter
    Private fullPathFileName = "c:\some folder\path\fileName.txt"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        sw = New StreamWriter(fullPathFileName, True)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        ' ... do something in here, probably in a loop ...

        While (someConditions)

            ' Write to "sw":
            sw.WriteLine("New Data Line Appended!")

        End While

    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If Not IsNothing(sw) Then
            sw.Close()
        End If
    End Sub

End Class

*The above has zero exception handling, which should always be added when dealing with files.

3
MilletSoftware On
Using writer As New StreamWriter("c:\temp\myLog.txt", True)
    writer.WriteLine("my Log Message")
End Using