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)
Solution
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(...))
{
}


very good post !!
solve my problem
thank’s
this post solve my problem too
thank u very much!
Excellent solution to quickly get result. Thank you for your precious time.
Sudhagar Ramiah
Simply it is excellent solution.
This suggestion solve my problem.
Thank you very much.
Atanu Kole
This solution is amazing,
I spent 2 days before coming to this page.
Its very nice, worked.
May God Help U.
Thank you,
Just I want to tell you, Thanks a million
Great solution. I specially like the alternative solution “USING”. This is very modular approcah to the programming. Thanks for sharing your experiance.
Nice this is the solution thx a lot
This worked like a charm…thank you so much
Thank you so much for resolving this issue!
Thank you very much dude really its very much helpful for me this solved my problem.
Thanks!
Thanks solved the issue I had from quite some time.
Thanks buddy!!!
It was really a great help.
I was struggling with this issue from last 4 days.
i didnt understand what dispolse mean
Ismaeel, thanks for noticing the typo. I’ve just corrected it.