Log error messages to a text file in a WINDOWS FORM APPLICATION

In a Windows Forms application, while performing an action in a functionality, exceptions might be caught or error messages have to be logged to check where exactly the particular error has occurred or exception has been caught. The error log can be logged into either a table in a database or to a text file. Here is a function used to log the errors into a text file. The logs will be appended to the previous logs in the file
Find the code below.

//Function LogMessage input errorMessage
public void LogMessage(string errorMessage)
//Logs the error in the Log file
string path = "Error" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
//Check for the file exists, or create a new file
if (!File.Exists(System.IO.Path.GetFullPath(path)))
using (StreamWriter w = File.AppendText(System.IO.Path.GetFullPath(path)))
// using the stream writer class write
// log message in a file.
w.WriteLine("\r\nLog Entry : ");
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
string err = "Error Message:" + errorMessage;
w.WriteLine ("____________________________________________________________________");
catch (Exception ex)

This function can be called where a condition check is handled or even in the catch block.


Guest Author: All Blond13 Feb 2012

That function will throw error on compile at :


No definition exists within scope of the code for it.

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: