acadia acadia - 8 months ago 82 Question

Creating and appending text to txt file in VB.NET

Using VB.NET, I am trying to create a text file if it doesn't exist or append text to it if exists.

For some reason, though it is creating the text file I am getting an error saying process cannot access file.

And when I run the program it is writing text, but how can I make it write in new line?

Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"

Dim sw As StreamWriter
Dim fs As FileStream = Nothing

If (Not File.Exists(strFile)) Then
fs = File.Create(strFile)
sw = File.AppendText(strFile)
sw.WriteLine("Start Error Log for today")

Catch ex As Exception
MsgBox("Error Creating Log File")
End Try
sw = File.AppendText(strFile)
sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)

End If


Try this:

Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
    sw.WriteLine( _
        IIf(fileExists, _
            "Error Message in  Occured at-- " & DateTime.Now, _
            "Start Error Log for today"))
End Using