Home > C#

Write to Log File in .NET - C#

18. March 2009

So this is pretty much for my use because I always seems to lose the code each time I need to write to a log file so I'm posting it on here now for my reference, and also for everyone else's reference.  I actually keep this piece of code in a class called util.  so I'm just going to paste the function and also the setting in the config file. 

Setting in Config File

<add key="logFilePath" value="D:\logFile.txt"/>

public static void function in util.cs

public static void writeToLogFile(string logMessage)
{
    string strLogMessage = string.Empty;
    string strLogFile = System.Configuration.ConfigurationManager.AppSettings["logFilePath"].ToString();
    StreamWriter swLog;
           
    strLogMessage = string.Format("{0}: {1}", DateTime.Now, logMessage);

    if (!File.Exists(strLogFile))
    {
        swLog = new StreamWriter(strLogFile);
    }
    else
    {
        swLog = File.AppendText(strLogFile);
    }

    swLog.WriteLine(strLogMessage);
    swLog.WriteLine();

    swLog.Close();

}

 

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

C#

blog comments powered by Disqus