Export (0) Print
Expand All

How to: Open and Append to a Log File

StreamWriter and StreamReader write characters to and read characters from streams. The following code example opens the log.txt file for input, or creates the file if it does not already exist, and appends information to the end of the file. The contents of the file are then written to standard output for display. As an alternative to this example, the information could be stored as a single string or string array, and the WriteAllText or WriteAllLines method could be used to achieve the same functionality.

Note Note

Visual Basic users may choose to use the methods and properties provided by the Log class or FileSystem class for creating or writing to log files.

Imports System
Imports System.IO

Class DirAppend
    Public Shared Sub Main()
        Using w As StreamWriter = File.AppendText("log.txt")
            Log("Test1", w)
            Log("Test2", w)
        End Using 

        Using r As StreamReader = File.OpenText("log.txt")
        End Using 
    End Sub 

    Public Shared Sub Log(logMessage As String, w As TextWriter)
        w.Write(vbCrLf + "Log Entry : ")
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), _
        w.WriteLine("  :")
        w.WriteLine("  :{0}", logMessage)
        w.WriteLine ("-------------------------------")
    End Sub 

    Public Shared Sub DumpLog(r As StreamReader)
        Dim line As String
        line = r.ReadLine()
        While Not (line Is Nothing)
            line = r.ReadLine()
        End While 
    End Sub 
End Class
© 2015 Microsoft