Moving / Deleting Files That Were Attachments After Sending Email in .NET

I recently worked on some code that attached some files to an email in .NET. After the email is sent, the code tries to move the files that were attached to a "Sent" directory, but it was failing with the error "The process cannot access the file because it is being used by another process." The cause was that the MailMessage class implements IDisposable, and even though I'm often very cognizant / responsible when it comes to disposing of IDisposable objects, in this case, I missed it. Once I disposed of the mail message, I was able to move those files. And I now lower my head in shame...

Here's the corrected code as an example. Wrapping the mailMessage variable inside a using block implicitly calls Dispose() at the end of the block.

using (var mailMessage = CreateMailMessage(emailTo, emailFrom, body, emailSubject))
{
    CreateEmailAttachments(mailMessage, attachmentFilenames);
    _smtpManager.Send(mailMessage);
}
I've been meaning to write a blog post about IDisposable for awhile now, and since I ran into this issue I think it's about time I got around to it.

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

Silent Renew and the "login_required" Error When Using oidc-client