Writing to a log file in C#

August 21st, 2007    1 Comment

Here's a chunk of code that will write values to a log file. If the file doesn't exist, it creates it, otherwise it just appends to the existing file. You need to add "using System.IO;" at the top of your code, if it's not already there.

string strLogText = "Some details you want to log.";

// Create a writer and open the file:
StreamWriter log;

if (!File.Exists("logfile.txt"))
{
  log = new StreamWriter("logfile.txt");
}
else
{
  log = File.AppendText("logfile.txt");
}

// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();

// Close the stream:
log.Close();

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Comments

  1. User Gravatar Dave said:

    September 5th, 2007 at 6:49 am (#)

    Why don't you just use log4net from Apache?

Leave a comment