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.
w.Close()
' Open and read the file.
Dim r As StreamReader = File.OpenText("log.txt")
DumpLog(r)
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)
w.WriteLine("-------------------------------")
' Update the underlying file.
w.Flush()
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
Console.WriteLine(line)
line = r.ReadLine()
End While
r.Close()
End Sub
End Class
[C#]
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.
w.Close();
// 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(),
DateTime.Now.ToLongDateString());
w.WriteLine(" :");
w.WriteLine(" :{0}", logMessage);
w.WriteLine ("-------------------------------");
// Update the underlying file.
w.Flush();
}
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)
{
Console.WriteLine(line);
}
r.Close();
}
}
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