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

时间:2015-03-31 20:39:00

标签: vb.net winforms filestream streamwriter

我试图将一些文本行写入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

然后我尝试从另一个已经将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行,但我什么都没得到。我看不出我做错了什么。

1 个答案:

答案 0 :(得分:1)

它对我有用,但如果代码对你不起作用,你可以使用这样的代码......

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