Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process cannot access the file "MyFile.log" because it is being used by another process

Tags:

c#

.net

log4net

I am getting

The process cannot access the file "MyFile.log" because it is being used by another process.

while I am doing this

File.SetAttributes(filename,FileAttributes.Normal)

using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
    // Do stuff with log4net log
}

I have read other posts but they all suggest what I am already doing. Any other suggestions?

Thanks.

like image 339
user9969 Avatar asked Jan 03 '12 09:01

user9969


1 Answers

Try to configure log4net with a minimal lock:

<appender name="FileAppender" type="log4net.Appender.FileAppender">
    ...
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
   ...
</appender>

have a look here for better explanation.

Alternatively, try to open the log file with:

     using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))
    {...
}

or check this project:Tailf In any case, remove the SetAttributes() part that could not work. Tailf Project Description Tailf is a C# implementation of the tail -f command available on unix/linux systems. Differently form other ports it does not lock the file in any way so it works even if other rename the file: this is expecially designed to works well with log4net rolling file appender.

like image 175
Felice Pollano Avatar answered Nov 28 '22 09:11

Felice Pollano