C# how to correctly dispose of an SmtpClient?
Posted
by JL
on Stack Overflow
See other posts from Stack Overflow
or by JL
Published on 2010-05-06T12:37:07Z
Indexed on
2010/05/06
12:48 UTC
Read the original article
Hit count: 363
c#
VS 2010 code analysis reports the following:
Warning 4 CA2000 : Microsoft.Reliability : In method 'Mailer.SendMessage()', object 'client' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'client' before all references to it are out of scope.
My code is :
public void SendMessage()
{
SmtpClient client = new SmtpClient();
client.Send(Message);
client.Dispose();
DisposeAttachments();
}
How should I correctly dispose of client?
Update: to answer Jons question, here is the dispose attachments functionality:
private void DisposeAttachments()
{
foreach (Attachment attachment in Message.Attachments)
{
attachment.Dispose();
}
Message.Attachments.Dispose();
Message = null;
}
© Stack Overflow or respective owner