Is it acceptable to do the following :
Attachment attachment = new Attachment(path, mediaType);
//Do other stuff...
using(attachment)
{
//Send email
}
I usually create my disposable directly inside the using statement but in this case it's a bit complicated.
Background
I just encountered a bug in a legacy application where the email attachment is not releasing the file handle. So, the file can no longer be modified as it's already in use.
It seems the problem is that the programmer forgot to call Dispose() on the attachment. Usually, this would be an easy problem to solve, but in this case, because of the structure of the code, I can't easily put the attachment inside a using directly when it's created.
Is the alternative above a good compromise?
The real issue is that you shouldn't need to Dispose the Attachment because the MailMessage will dispose of the attachment automatically when and IF you call Dispose on MailMessage.
using(MailMessage message = ...)
{
}
Looking at the internals of the MailMessage class, you'll see that an Attachment collection (attachments) is being disposed:
protected virtual void Dispose(bool disposing)
{
if (disposing && !disposed)
{
disposed = true;
if(views != null){
views.Dispose();
}
if(attachments != null){
attachments.Dispose();
}
if(bodyView != null){
bodyView.Dispose();
}
}
}
https://referencesource.microsoft.com/#System/net/System/Net/mail/MailMessage.cs