StreamWriter 文本文件已创建但不包含任何行

StreamWriter text file gets created but contains no lines

我正在尝试将一些文本行写入 Windows 表单应用程序中的一个小日志文件,但我不明白为什么没有写入任何行。文件创建正常,以下所有操作都没有错误地执行,但是当我用记事本打开新文件时,没有任何行。关键片段如下:

    Dim sFileName = App_Path() & "\logs\" & sJobName & ".log"
    Try
        Using fs As FileStream = New FileStream(sFileName, FileMode.Append, FileAccess.Write)
            Using w As StreamWriter = New StreamWriter(fs)
                Dim s As String = "Beginning execution (JobName=" & sJobName & ")"
                Log(s, w)
                s = "Connection in effect: " & BuildConnectString()
                Log(s, w)
                Dim loader As New Importer
                loader.LoadData(Me.txtFN.Text, w)
            End Using
        End Using
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

Public Sub Log(logMessage As String, w As StreamWriter)
    w.WriteLine("{0} {1}: {2}", DateTime.Now.ToLongTimeString(), _
        DateTime.Now.ToShortDateString(), logMessage)
End Sub

然后我尝试从另一个 class 写入此日志,该日志已作为参数传递给 StreamWriter:

Public Function LoadData(ByRef filename As String, _
                         ByRef w As StreamWriter) As String
    Dim s As String = "Test logging from loader class"
    Mainform.Log(s, w)

在这个小测试中,我希望看到 3 行,但我什么也没看到。我看不出我做错了什么。

它适用于我,但如果代码不适合你,你可以使用这样的代码...

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim sFileName = App_Path() & "\logs\" & sJobName & ".log"
    Try
        Dim s As String = "Beginning execution (JobName=" & sJobName & ")"
        Log(s, sFileName)
        s = "Connection in effect: " & BuildConnectString()
        Log(s, sFileName)
        Dim loader As New Importer
        loader.LoadData(Me.txtFN.Text, sFileName)
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Public Sub Log(logMessage As String, StrPath As String)
    IO.File.AppendAllText(StrPath, String.Format("{0} {1}: {2}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToShortDateString(), logMessage) + vbCrLf)
End Sub

Public Function LoadData(ByRef filename As String, _
                     StrPath As String) As String
    Dim s As String = "Test logging from loader class"
    Log(s, StrPath)
End Function