【发布时间】:2011-02-20 21:00:54
【问题描述】:
我正在使用 System.Net.Mail 在 asp.net 中发送邮件.. 附件作为附件邮件发送后如何删除.. 我尝试使用 File.Delete 方法..但我收到此错误.. 该进程无法访问文件 path\fun.jpg',因为它正被另一个进程使用。 谢谢
【问题讨论】:
标签: c# email-attachments
我正在使用 System.Net.Mail 在 asp.net 中发送邮件.. 附件作为附件邮件发送后如何删除.. 我尝试使用 File.Delete 方法..但我收到此错误.. 该进程无法访问文件 path\fun.jpg',因为它正被另一个进程使用。 谢谢
【问题讨论】:
标签: c# email-attachments
使用完 MailMessage 后将其丢弃。 在您完成此操作之前,它仍会锁定您作为附件添加的文件。
var filePath = "C:\\path\\to\\file.txt";
var smtpClient = new SmtpClient("mailhost");
using (var message = new MailMessage())
{
message.To.Add("to@domain.com");
message.From = new MailAddress("from@domain.com");
message.Subject = "Test";
message.SubjectEncoding = Encoding.UTF8;
message.Body = "Test " + DateTime.Now;
message.Attachments.Add(new Attachment(filePath));
}
if (File.Exists(filePath)) File.Delete(filePath);
Console.WriteLine(File.Exists(filePath));
输出:假
我想如果您在处理消息后仍然有锁定文件的东西,那么您可能对文件有另一个锁定,但是没有代码,我们无法帮助您。
【讨论】:
发送邮件后不能删除附件,发送前可以删除。
错误说明了什么,您提到的路径正在使用其他进程。
MailMessage Message = new MailMessage();
Message.Subject = "Attachment Test";
Message.Body = "Check out the attachment!";
Message.To.Add("webmaster@15Seconds.com");
Message.From = "someone@somedomain.com";
Message.Attachments.Add(new Attachment(memorystream, "test.txt", MediaTypeNames.Application.Text));
请注意,我们从 MemoryStream 中创建了附件,并且我们必须为附件命名任何我们想要的名称。第二个参数中的附件名称是邮件中文件的名称,而不是本地系统硬盘上的名称。事实上,附件永远不会进入本地硬盘驱动器。第三个参数是附件的 Mime 类型,在我们的例子中是文本。
编辑:use Dispose() the mail
【讨论】:
扩展 MailMessage 类是解决此问题并减少再次遇到此问题的机会的好方法...
class MyMailMessage : MailMessage, IDisposable
{
private List<string> _tempFiles = new List<string>();
public void Attach(string filename)
{
base.Attachments.Add(new Attachment(filename));
this._tempFiles.add(filename);
}
new public void Dispose()
{
base.Dispose();
this._tempFiles.Foreach(x => File.Delete(x));
}
}
...并记住与“使用”构造一起使用(无论如何您都应该使用它)...
using(SmtpClient client = GetMySmtpClient())
using(MyMailMessage msd = new MyMailMessage())
{
msg.Attach(filename);
client.send(msg);
}
【讨论】:
如果您的邮件有很多附件
List<Attachments> lstAtt = new List<Attachments>();
Attachment att = new Attachment(file);
lstAtt.Add(att);
//finally
foreach(var a in lstAtt)
{
a.Dispose();
}
//delete file
【讨论】:
您只需要在删除文件之前释放消息对象。例如:
Dim message As New MailMessage
message.From = New MailAddress(fromEmail, fromName)
message.Subject = subject
message.CC.Add(toCCEmail)
message.Bcc.Add(toBCCEmail)
Dim attach As Attachment = New Attachment(attachmentPath)
message.Attachments.Add(attach)
message.IsBodyHtml = True
message.Body = body
mailClient.Send(message)
message.Dispose() 'Add this line to dispose the message!
【讨论】: