在VB.NET中使用StreamWriter不会写入文本文件

时间:2015-07-23 08:08:13

标签: .net vb.net logging streamwriter

我已阅读这些来源(first Stack Overflow questionsecond Stack Overflow questionthird Stack Overflow questionfourth Stack Overflow questionMicrosoft streamwriter),但这并未解决问题。

我在下面有这段代码。

第一

Private Sub WritePropertyLog(ByVal folderPath As String, ByVal file_name As String, ByVal property_cd As String, _
                ByVal property_name As String, ByVal status As String)

    Using w As StreamWriter = File.AppendText("Files\" + "DS_IKO_" + Date.Today.ToString("yyyyMMdd") + ".log")
        PropertyLog(folderPath, file_name, property_cd, property_name, status, w)
    End Using

End Sub

Private Sub PropertyLog(ByVal folderPath As String, ByVal file_name As String, ByVal property_cd As String, _
                ByVal property_name As String, ByVal status As String, ByVal w As TextWriter)

    w.Write(DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + ", ")
    w.WriteLine("{0}, {1}, {2}, {3}, {4}", folderPath, file_name, property_cd, property_name, status)

End Sub

SECOND

' Logging each record ----------
Private Sub WriteRecordLog(ByVal row_number As String, ByVal columnB As String, ByVal columnC As String, _
                ByVal columnD As String, ByVal sekisan_cd As String, ByVal propertyCd As String, ByVal filename As String)

    Dim strFile As String = "Files\" + propertyCd = "_" + filename + "_" + Date.Now.ToString("yyyyMMdd") + ".log"
    Using writer As StreamWriter = File.AppendText(strFile)
        RecordLog(row_number, columnB, columnC, columnD, sekisan_cd, writer)
    End Using

End Sub

Private Sub RecordLog(ByVal row_number As String, ByVal columnB As String, ByVal columnC As String, _
                ByVal columnD As String, ByVal sekisan_cd As String, ByVal w As TextWriter)

    w.WriteLine("{0}, {1}, {2}, {3}, {4}", row_number, columnB, columnC, columnD, sekisan_cd)

End Sub

我正在尝试创建一个日志文件,正如您所看到的,除了变量之外,两者之间没有太大区别。 FIRST 代码实际输出或写入.log,但 SECOND 代码不会。我需要两个代码来编写不同的日志,第二个代码首先执行,并执行比第一个代码更多的时间。

问题是什么?

我尝试在第二个代码中添加它:

    Dim fs As FileStream = Nothing
    If (Not File.Exists(strFile)) Then
        fs = File.Create(strFile)
    End If

我甚至尝试了.flush().close()以及其他方式:

Using
End Using

但没有任何作用。

1 个答案:

答案 0 :(得分:1)

这是你的问题:

Dim strFile As String = "Files\" + propertyCd = "_" + filename + "_" + Date.Now.ToString("yyyyMMdd") + ".log"

特别是这部分:

propertyCd = "_"

这是一种比较,并返回TrueFalse

一般情况下,我会使用String.Format作为您的文件名,并使用Path.Combine来构建路径。

Dim file = String.Format("{0}_{1}_{2}.log", 
    propertyCd, filename, Date.Now.ToString("yyyyMMdd")) 
Dim strFile As String = Path.Combine("Files", file)

此外,使用调试器在运行时检查变量的值。