Search code examples
c#system.net.mail

Closing file attached to email System.Net.Mail


I have a file I attach to email in an ASP.NET application. The problem is that the process will not let go of the file. How do I close the file in the method so I can use it in my program again?

Attachment data = new Attachment(@"\\WIN-UWPWZ7Z3RKX\wwwroot\katipro\skus.txt");
m.Attachments.Add(data); 

SmtpClient s = new SmtpClient("smtp.gmail.com", 587);
s.Send(m);

After I call the method it does not allow me to write to that file again without an error.


Solution

  • System.Net.Mail.Attachment implements IDisposable. You need to dispose your attachment.

    using(Attachment data = new Attachment(@"\\WIN-UWPWZ7Z3RKX\wwwroot\katipro\skus.txt"))
    {
        m.Attachments.Add(data); 
    
        SmtpClient s = new SmtpClient("smtp.gmail.com", 587);
        s.Send(m);
    }
    

    Likewise, if you are using .NET Framework 4.0; SmtpClient is disposable as well. So dispose of it if you are using the 4.0 Framework. You should always dispose of things that implement the IDisposable interface when you are done using them.