Write Log details to a text file C#

Posted by Techie Cocktail | 4:23 PM | | 0 comments »

Lot of times we are unable to detect an issue in the code. Below function can do logging for you in a text file in your application path.

Checkout.


static private void WriteLogsToTextFile(string logStr)
{
try
{
if (ConfigurationSettings.AppSettings["beginLogging"].ToString().Equals("true"))
{
if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "LogFile.txt"))
{
using (StreamWriter sw = File.CreateText(AppDomain.CurrentDomain.BaseDirectory + "LogFile.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + logStr);
sw.Close();
}
}
else using (StreamWriter sw = File.AppendText(AppDomain.CurrentDomain.BaseDirectory + "LogFile.txt"))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + logStr);
sw.Close();
}
}
}
catch (Exception ex)
{
//display error.
}
}

0 comments