C# 该进程无法访问该文件,因为它正被另一个进程使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1625042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The process cannot access the file because it is being used by another process
提问by pistacchio
I'm trying to read a log file of log4net:
我正在尝试读取 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.
我得到了该主题指定的异常。我猜 log4Net 对文件持有独占锁,但是,例如 Notepad++ 可以读取文件,我猜在技术上可以做到这一点。
Any help?
有什么帮助吗?
采纳答案by Guillaume
using (FileStream fs =
new FileStream(filePath,
FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
//...
http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx
http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx
Your log may be write locked, so try with FileShare.ReadWrite.
您的日志可能被写锁定,因此请尝试使用 FileShare.ReadWrite。
回答by Abel
Try to add the FileShare option, see if that helps:
尝试添加 FileShare 选项,看看是否有帮助:
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.
编辑:更正的代码,FileShare.Read
但不是FileShare.ReadWrite
诀窍(正如纪尧姆所展示的那样)。原因:您想打开您的文件并允许其他人同时读取和写入它。