in src/log4net/Appender/RollingFileAppender.cs [1177:1229]
protected void DeleteFile(string fileName)
{
LogLog.Debug(_declaringType, $"Trying to delete [{fileName}]");
if (!FileExists(fileName))
{
LogLog.Debug(_declaringType, $"[{fileName}] does not exist");
return;
}
// We may not have permission to delete the file, or the file may be locked
string fileToDelete = fileName;
// Try to move the file to temp name.
// If the file is locked we may still be able to move it
string tempFileName = fileName + "." + Environment.TickCount + ".DeletePending";
try
{
using (SecurityContext?.Impersonate(this))
{
System.IO.File.Move(fileName, tempFileName);
}
fileToDelete = tempFileName;
}
catch (Exception e) when (!e.IsFatal())
{
LogLog.Debug(_declaringType, $"Exception while moving file to be deleted [{fileName}] -> [{tempFileName}]", e);
}
// Try to delete the file (either the original or the moved file)
try
{
using (SecurityContext?.Impersonate(this))
{
System.IO.File.Delete(fileToDelete);
}
LogLog.Debug(_declaringType, $"Deleted file [{fileName}]");
}
catch (Exception e) when (!e.IsFatal())
{
if (fileToDelete == fileName)
{
// Unable to move or delete the file
ErrorHandler.Error($"Exception while deleting file [{fileToDelete}]", e, ErrorCode.GenericFailure);
}
else
{
// ReSharper disable once GrammarMistakeInComment
// Moved the file, but the delete failed. File is probably locked.
// The file should automatically be deleted when the lock is released.
LogLog.Debug(_declaringType, $"Exception while deleting temp file [{fileToDelete}]", e);
}
}
}