pistacchio
pistacchio

Reputation: 58953

The process cannot access the file because it is being used by another process

I'm trying to read a log file of log4net:

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)

and I get the Exception specified on the title. I guess log4Net is holding an exclusive lock on the file, but, as for example Notepad++ can read the file, I guess is technically possible to do this.

Any help?

Upvotes: 44

Views: 42775

Answers (2)

Guillaume
Guillaume

Reputation: 13138

using (FileStream fs = 
    new FileStream(filePath,
        FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
//...

https://learn.microsoft.com/en-us/dotnet/api/system.io.fileshare

Your log may be write locked, so try with FileShare.ReadWrite.

Upvotes: 85

Abel
Abel

Reputation: 57189

Try to add the FileShare option, see if that helps:

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

EDIT: corrected code, not FileShare.Read but FileShare.ReadWrite does the trick (as Guillaume showed as well). The reason: you want to open your file and allow others to read and write it at the same time.

Upvotes: 18

Related Questions