该进程无法访问该文件,因为该文件正由另一个进程使用

pis*_*hio 38 c#

我正在尝试读取log4net的日志文件:

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)
Run Code Online (Sandbox Code Playgroud)

我得到了关于该主题的Exception.我想log4Net对文件保持独占锁定,但是,例如Notepad ++可以读取文件,我想技术上可以做到这一点.

有帮助吗?

Gui*_*ume 72

using (FileStream fs = 
    new FileStream(filePath,
        FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
//...
Run Code Online (Sandbox Code Playgroud)

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

您的日志可能被写入锁定,因此请尝试使用FileShare.ReadWrite.

  • +1用于添加非常有用的链接.至少对于我来说 :-) (3认同)
  • This doesn't work for me. It still says that the file is used by another process. Any idea why? (2认同)

Abe*_*bel 14

尝试添加FileShare选项,看看是否有帮助:

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Run Code Online (Sandbox Code Playgroud)

编辑:更正的代码,FileShare.Read但不是,但FileShare.ReadWrite诀窍(如Guillaume所示).原因是:您希望打开文件并允许其他人同时读取和写入文件.