How to empty contents of a log file being used by the same program

942 views Asked by At

I have a C# application which uses log4net to write some log outputs in a file names "logfile.txt" residing in the application directory. I want to empty the contents of the file as soon as it reaches a size of 10GB.

For that I'm using a timer which keeps checking whether the size of the file crosses 10GB. But I cannot perform any operation on "logfile.txt" since it is being used by other threads to write log outputs and it's throwing me,

System.IO.IOException "The process cannot access the file 'C:\Program Files\MyApps\TestApp1\logfile.txt' because it is being used by another process."

Here is the code of the timer which checks the size of the file "logfile.txt"

private void timer_file_size_check_Tick(object sender, EventArgs e)
{
    try
    {
        string log_file_path = "C:\\Program Files\\MyApps\\TestApp1\\logfile.txt";
        FileInfo f = new FileInfo(log_file_path);
        bool ex;
        long s1;
        if (ex = f.Exists)
        {
            s1 = f.Length;
            if (s1 > 10737418240)
            {
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();

                File.Delete(log_file_path);
                //File.Create(log_file_path).Close();
                //File.Delete(log_file_path);
                //var fs = new FileStream(log_file_path, FileMode.Truncate);
            }
        }
        else
        {
            MDIParent.log.Error("Log file doesn't exists..");
        }
    }
   catch (Exception er)
    {
        MDIParent.log.Error("Exceptipon :: " + er.ToString());
    } 
}
1

There are 1 answers

0
Michał Komorowski On

You shouldn't delete a log file on your own because log4net can do it for you. If you use RollingFileAppender you can specify the maximum file size (maximumFileSize property). Additionally if you set maxSizeRollBackups property to 0, then the log file will be truncated when it reaches the limit. Please look at this question for an example.