Search code examples
vb.netfilestreamwriter

Log Writer not creating new line for each entry


I get the feeling this is something really simple, but I've tried I don't know how many permutations of vbNewLine, Environment.NewLine, sMessage & vbNewLine (or Environment.Newline) I've tried, or how many pages on this site, or through Google I've looked at but nothing has worked.

I even tried getting help from a VB.Net discord channel I'm a part of and they suggested to do the same things that I've done and the procedure is still writing each new log entry at the end of the previous one in a continuous string. My writer is below. Am I missing something simple?

Edit: The code that worked is below in case anyone else comes along with the same issue. If you want to see the original code it's in the edit log.

Option Explicit On
Imports System.IO

Public Class WriteroLog
    Public Shared Sub LogPrint(sMessage As String)
        Dim AppPath As String = My.Application.Info.DirectoryPath

        If File.Exists($"{AppPath}\Log.txt") = True Then
            Try
                Using objWriter As StreamWriter = File.AppendText($"{AppPath}\Log.Txt")
                    objWriter.WriteLine($"{Format(Now, "dd-MMM-yyyy HH:mm:ss")} – {sMessage}")
                    objWriter.Close()
                End Using
            Catch ex As Exception
                MsgBox(ex)
                Return
            End Try
        Else
            Try
                Using objWriter As StreamWriter = File.CreateText($"{AppPath}\Log.Txt")
                    objWriter.WriteLine($"{Format(Now, "dd-MMM-yyyy HH:mm:ss")} – {sMessage}")
                    objWriter.Close()
                End Using

            Catch ex As Exception
                MsgBox(ex)
                Return
            End Try
        End If
    End Sub
End Class

Solution

  • The File.AppendText() method creates a new StreamWriter that is then used to append Text to the specified File.
    Note, reading the Docs about this method, that you don't need to verify whether the File already exists: if it doesn't, the File is automatically created.

    As a side note, when creating a Path, it's a good thing to use the Path.Combine method: it can prevent errors in the path definition and handles platform-specific formats.

    Your code could be simplified as follows:

    Public Shared Sub LogPrint(sMessage As String)
        Dim filePath As String = Path.Combine(Application.StartupPath, "Log.Txt")
    
        Try
            Using writer As StreamWriter = File.AppendText(filePath)
                writer.WriteLine($"{Date.Now.ToString("dd-MMM-yyyy HH:mm:ss")} – {sMessage}")
            End Using
        Catch ex As IOException
            MsgBox(ex)
        End Try
    End Sub