IOException: The process cannot access the file 'file path' because it is being used by another process

前端 未结 10 2076
陌清茗
陌清茗 2020-11-22 00:13

I have some code and when it executes, it throws a IOException, saying that

The process cannot access the file \'filename\' because it

10条回答
  •  一个人的身影
    2020-11-22 00:22

    As other answers in this thread have pointed out, to resolve this error you need to carefully inspect the code, to understand where the file is getting locked.

    In my case, I was sending out the file as an email attachment before performing the move operation.

    So the file got locked for couple of seconds until SMTP client finished sending the email.

    The solution I adopted was to move the file first, and then send the email. This solved the problem for me.

    Another possible solution, as pointed out earlier by Hudson, would've been to dispose the object after use.

    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
                }
    } 
    

提交回复
热议问题