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 th开发者_如何学运维e 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.
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.
You do not need to dispose the attachments when you dispose the MailMessage. If you look at the internal implementation, the MailMessage does already dispose the attachments itself.
// MailMessage.cs
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();
}
}
}
Code from https://referencesource.microsoft.com/#System
You need to dispose all IDisposable
objects you use for them to release unmanaged resources such as file handles.
using(MailMessage m = ...)
{
...
using (Attachment data = ...)
{
...
using (SmtpClient s = ...)
{
...
}
}
}
The Attachment
implements IDisposable
; you need to dispose the instance to release its resources, after you send the message.
...
s.Send(m)
data.Dispose();
精彩评论