我有一些代码,当它执行时,它抛出一个IOException,说

进程无法访问文件'filename',因为它正在被 另一个进程

这意味着什么?我能做些什么?


当前回答

正如本文中的其他回答所指出的,要解决这个错误,您需要仔细检查代码,以了解文件被锁定的位置。

在我的例子中,我在执行移动操作之前将文件作为电子邮件附件发送出去。

所以文件被锁定了几秒钟,直到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
            }
} 

其他回答

我有下面的场景会导致同样的错误:

上传文件到服务器 然后在旧文件上传后删除它们

大多数文件都很小,但也有少数文件很大,因此试图删除这些文件会导致无法访问文件的错误。

然而,要找到这个问题并不容易,解决方法很简单,就是“等待任务完成执行”:

using (var wc = new WebClient())
{
   var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
   tskResult.Wait(); 
}

在上传图像时出现问题,无法删除并找到解决方案。gl高频

//C# .NET
var image = Image.FromFile(filePath);

image.Dispose(); // this removes all resources

//later...

File.Delete(filePath); //now works

我有一个非常具体的情况,我得到了一个“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;
    }
});

我遇到了这个问题,通过下面的代码解决了这个问题

var _path=MyFile.FileName;
using (var stream = new FileStream
    (_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  { 
    // Your Code! ;
  }

在我的案例中,这个问题通过打开文件进行共享写/读解决了。共享读写的代码示例如下:— 流的作家

using(FileStream fs = new FileStream("D:\\test.txt", 
FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (StreamWriter sw = new StreamWriter(fs))
{
    sw.WriteLine("any thing which you want to write");
}

流的读者

using (FileStream fs = new FileStream("D:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader rr=new StreamReader(fs))
{
    rr.ReadLine())
}