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.

System_CAPS_ICON_note.jpg 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.

using System;
using System.IO;

class DirAppend
    public static void Main()
        using (StreamWriter w = File.AppendText("log.txt"))
            Log("Test1", w);
            Log("Test2", w);
        using (StreamReader r = File.OpenText("log.txt"))

    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 ("-------------------------------");

    public static void DumpLog(StreamReader r)
        string line;
        while ((line = r.ReadLine()) != null)

How to: Enumerate Directories and Files
How to: Read and Write to a Newly Created Data File
How to: Read Text from a File
How to: Write Text to a File
How to: Read Characters from a String
How to: Write Characters to a String
File and Stream I-O