System.IO.IOException: The process cannot access the file used as attachment with MailMessage

Recently I had to improve the mechanism of sending emails so that files can be attached to it. As I used MailMessage it seemed to be an easy task, especially that MSDN provided an example of how to do it. They assumed there that the file used as the attachment was already on the server and it shouldn’t be deleted after the email is sent.

However, I had to upload this file and therefore remove it afterwards. At the end of the day I ended up with an exception thrown while removing the file:

System.IO.IOException: The process cannot access the file 'XXX' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.Delete(String path)


There’s a simple fix for that. After the email is sent but before the uploaded attachment is deleted use Dispose() method of MailMessage. This way you will release all resources used by MailMessage.

Alternatively you can create MaillMessage within using block. As a result all resources will be released (disposed or closed) automatically when execution of the block completes.

using(MailMessage email = new MailMessage(...))
Previous Post
Next Post