我有一些代码,当它执行时,它抛出一个IOException,说
进程无法访问文件'filename',因为它正在被 另一个进程
这意味着什么?我能做些什么?
我有一些代码,当它执行时,它抛出一个IOException,说
进程无法访问文件'filename',因为它正在被 另一个进程
这意味着什么?我能做些什么?
当前回答
问题
一个是绑定打开文件System.IO.File。使用此方法打开(path, FileMode),并希望对文件进行共享访问
如果你读了System.IO.File的文档。Open(path, FileMode),它显式地表示它不允许共享
解决方案
你必须使用其他覆盖文件共享
using FileStream fs = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
文件共享。读
其他回答
问题
一个是绑定打开文件System.IO.File。使用此方法打开(path, FileMode),并希望对文件进行共享访问
如果你读了System.IO.File的文档。Open(path, FileMode),它显式地表示它不允许共享
解决方案
你必须使用其他覆盖文件共享
using FileStream fs = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
文件共享。读
我有一个非常具体的情况,我得到了一个“IOException:进程不能访问文件'文件路径'”的行
File.Delete(fileName);
在一个NUnit测试中,看起来像这样:
Assert.Throws<IOException>(() =>
{
using (var sr = File.OpenText(fileName) {
var line = sr.ReadLine();
}
});
File.Delete(fileName);
NUnit 3使用了所谓的“隔离上下文”来进行异常断言。这可能运行在一个单独的线程上。
我的解决办法是把文件。在同一上下文中删除。
Assert.Throws<IOException>(() =>
{
try
{
using (var sr = File.OpenText(fileName) {
var line = sr.ReadLine();
}
}
catch
{
File.Delete(fileName);
throw;
}
});
使用FileShare修复了我打开文件的问题,即使它被另一个进程打开。
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}
我下面的代码解决这个问题,但我建议 首先,你需要了解是什么导致了这个问题,并尝试通过修改代码来找到解决方案
我可以给出另一种方法来解决这个问题,但更好的解决方案是检查你的编码结构,并尝试分析是什么导致这种情况发生,如果你没有找到任何解决方案,那么你可以使用下面的代码
try{
Start:
///Put your file access code here
}catch (Exception ex)
{
//by anyway you need to handle this error with below code
if (ex.Message.StartsWith("The process cannot access the file"))
{
//Wait for 5 seconds to free that file and then start execution again
Thread.Sleep(5000);
goto Start;
}
}
正如本文中的其他回答所指出的,要解决这个错误,您需要仔细检查代码,以了解文件被锁定的位置。
在我的例子中,我在执行移动操作之前将文件作为电子邮件附件发送出去。
所以文件被锁定了几秒钟,直到SMTP客户端完成发送电子邮件。
我采取的解决方案是先移动文件,然后再发送电子邮件。这为我解决了问题。
另一个可能的解决方案,正如Hudson之前指出的,应该是在使用后处理对象。
public static SendEmail()
{
MailMessage mMailMessage = new MailMessage();
//setup other email stuff
if (File.Exists(attachmentPath))
{
Attachment attachment = new Attachment(attachmentPath);
mMailMessage.Attachments.Add(attachment);
attachment.Dispose(); //disposing the Attachment object
}
}