This documentation is archived and is not being maintained.

Opening and Appending 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.

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Class DirAppend
    Public Shared Sub Main()
        Dim w As StreamWriter = File.AppendText("log.txt")
        Log("Test1", w)
        Log("Test2", w)
        ' Close the writer and underlying file.
        ' Open and read the file.
        Dim r As StreamReader = File.OpenText("log.txt")
    End Sub
    Public Shared Sub Log(ByVal logMessage As String, ByVal w As TextWriter)
        w.Write(ControlChars.CrLf & "Log Entry : ")
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString())
        w.WriteLine("  :")
        w.WriteLine("  :{0}", logMessage)
        ' Update the underlying file.
    End Sub
    Public Shared Sub DumpLog(ByVal r As StreamReader)
        ' While not at the end of the file, read and write lines.
        Dim line As String
        line = r.ReadLine()
        While Not line Is Nothing
            line = r.ReadLine()
        End While
    End Sub
End Class

using System;
using System.IO;
class DirAppend
    public static void Main(String[] args)
        StreamWriter w = File.AppendText("log.txt");
        Log ("Test1", w);
        Log ("Test2", w);
        // Close the writer and underlying file.
        // Open and read the file.
        StreamReader r = File.OpenText("log.txt");
        DumpLog (r);
    public static void Log (String logMessage, TextWriter w)
        w.Write("\r\nLog Entry : ");
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
        w.WriteLine("  :");
        w.WriteLine("  :{0}", logMessage);
        w.WriteLine ("-------------------------------");
        // Update the underlying file.
    public static void DumpLog (StreamReader r)
        // While not at the end of the file, read and write lines.
        String line;
        while ((line=r.ReadLine())!=null)

See Also

Creating a Directory Listing | Reading and Writing to a Newly Created Data File | Reading Text from a File | Writing Text to a File | Reading Characters from a String | Writing Characters to a String | Basic File I/O | StreamWriter | StreamReader | File.AppendText | File.OpenText | StreamReader.ReadLine