How to append a text file in C#

This code snippet shows how to append a text file in C#.

using System;

using System.IO;

 

 

namespace FileOperationsSample

{

    class Program

    {

 

        private static string logFileName = @"C:\Junk\MyLogfile.txt";

 

        public static void Main(String[] args)

        {

            using (StreamWriter writer = File.AppendText(logFileName))

            {

                Log("Test1", writer);

                Log("Test2", writer);

                writer.Close();

            }

            // Open and read the file.

            using (StreamReader reader = File.OpenText(logFileName))

            {

                DumpLog(reader);

            }

 

            Console.ReadLine();

        }

        public static void Log(String logMessage, TextWriter writer)

        {

            writer.Write("\r\nLog Entry : ");

            writer.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),

                DateTime.Now.ToLongDateString());

            writer.WriteLine("  :");

            writer.WriteLine("  :{0}", logMessage);

            writer.WriteLine("-------------------------------");

            // Update the underlying file.

            writer.Flush();

        }

        public static void DumpLog(StreamReader reader)

        {

            // While not at the end of the file, read and write lines.

            String line;

            while ((line = reader.ReadLine()) != null)

            {

                Console.WriteLine(line);

            }

            reader.Close();

        }

    }

 

}