Resource

How to append a text file in C#

Jul 06, 2009 Resources | C# Programming
To append a text or log file in C#, We writes the code for this and code is given below.
  • 0
  • 0
  • 38257
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();

        }

    }

 

}

 


Soft Dev

Software developer working with WPF and Silverlight.

  • 150rank
  • 2M readers
COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

TOP RESOURCES

MOST LIKED RESOURCES