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)
{
try
{
//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)))
{
File.Create(System.IO.Path.GetFullPath(path)).Close();
}
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(err);
w.WriteLine ("____________________________________________________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
LogMessage(ex.StackTrace);
}
}
This function can be called where a condition check is handled or even in the catch block.
That function will throw error on compile at :
DateTime.Now.ToString(CultureInfo.InvariantCulture));
No definition exists within scope of the code for it.