Create Log File in Asp.Net using C#

Create and Write Log File using C# in Asp.Net Application

November 21, 2020

In this article we will cover how to Create and Write Log File in Asp.Net Application using c#.

Create Log

This method will create log file with given name if it does not exists.

public void CreateLog(string logFileName)
{
    string directory = HttpContext.Current.Server.MapPath("~/App_Data/");
    string logFile = directory + "/" + logFileName;
 
    if (!File.Exists(logFile))
    {
        var file = File.Create(logFile);
        file.Close();
    }
}

Write Log

This method will create log file with given name if it does not exists and write data to it.

public void WriteLog(string logFileName)
{
    string directory = HttpContext.Current.Server.MapPath("~/App_Data/");
    string logFile = directory + "/" + logFileName;
 
    // Create file if it does not exists
    if (!File.Exists(logFile))
        CreateLog(logFileName);
 
    StreamWriter sw = new StreamWriter(logFiletrue);
    sw.WriteLine("********** Application Start Time**********");
    sw.WriteLine("********** {0} **********"DateTime.Now + " (System Time)");
    sw.Dispose();
    sw.Close();
}

Example

CreateLog("log.txt"); // Create Log File
WriteLog("log.txt"); // Write Log File
WriteLog("ErrorLog.txt"); // Create and Write Log File

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...