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

Using StreamWriter in VB.NET won't write to text file

我已经阅读了这些资料 (first Stack Overflow question, second Stack Overflow question, third Stack Overflow question, fourth Stack Overflow question and Microsoft 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

第二个

' 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 代码实际上输出或写入 .logSECOND 代码不会。我需要两个代码来编写不同的日志,并且 第二个代码 首先执行并且比 第一个代码 .

执行更多次

问题是什么?

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

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

我什至尝试了 .flush().close() 以及另一种不是的方式:

Using
End Using

但没有任何效果。

这是你的问题:

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

特别是这部分:

propertyCd = "_"

这是一个比较,returns 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)

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