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();
Potentially similar posts
- Maintaining a Flare project in Google Code – January 2010
- Syntax highlighting code snippets in WordPress – March 2009
- Notes on how I make a podcast – continued – August 2008
- Line breaks in WordPress – August 2008
- Related Topics in a popup not a dialog box – July 2008
September 5th, 2007 at 6:49 am (#)
Why don't you just use log4net from Apache?