43

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 topic. I guess log4Net is holdin 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?

Thilina H
  • 5,754
  • 6
  • 26
  • 56
pistacchio
  • 56,889
  • 107
  • 278
  • 420

2 Answers2

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

http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx

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

Guillaume
  • 12,824
  • 3
  • 40
  • 48
17

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.

Abel
  • 56,041
  • 24
  • 146
  • 247