目的
原始文件需要重复使用,修改,并发送邮件
错误
操作无法完成,因为文件已在 XXX 中打开
2021-11-19 09:05:00.008err–>System.IO.IOException: 文件“D:\JOB\Mails\repoprt\2021-11-18 20-00-00_main.xlsx”正由另一进程使用,因此该进程无法访问此文件。
在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
在 System.IO.File.InternalDelete(String path, Boolean checkHost)
在 System.IO.File.Delete(String path)
在 TrackOutDetailMails.job.TimeMails.post(String url, String content, String step) 位置 C:\Users\Administrator\Desktop\work\Report.Mail\TrackOutDetailMails\job\TimeMails.cs:行号 286
在 TrackOutDetailMails.job.TimeMails.Execute(IJobExecutionContext context) 位置 C:\Users\Administrator\Desktop\work\Report.Mail\TrackOutDetailMails\job\TimeMails.cs:行号 87
代码
try {
MailMessage mail = new MailMessage {
From = new MailAddress(MailUserName, MailDisplayName)
};
mail.To.Clear();
if (tos.Length == 0) {
return false;
}
//foreach (var address in List1.split(';'))
//{
// mailMessagePlainText.To.Add(new MailAddress(address.Trim(), ""));
//}
//添加收件人
tos.Distinct().ToList().ForEach(to => {
if (!string.IsNullOrEmpty(to)) {
mail.To.Add(new MailAddress(to.Trim(), ""));
}
});
//添加CC
if (cc != null) {
cc.Distinct().ToList().ForEach(c => {
mail.CC.Add(new MailAddress(c.Trim()));
});
}
//添加附件
if (attachment != null) {
attachment.Distinct().ToList().ForEach(a => {
Attachment item = new Attachment(a);
mail.Attachments.Add(item);
//item.Dispose();
});
}
mail.IsBodyHtml = isBodyHtml;
mail.Subject = subjectprefix + subject;
mail.Body = body;
mail.SubjectEncoding = Encoding.UTF8;
mail.Priority = MailPriority.High;
SmtpClient smtp = new SmtpClient(MailServer, 25);
smtp.Credentials = new NetworkCredential(MailName, MailPassword);
smtp.Send(mail);
//mail.Attachments.Dispose();
//mail.Attachments[0].Dispose();
//mail.Dispose();
return true;
} catch (Exception ) {
return false;
}
原因
//添加附件
if (attachment != null) {
attachment.Distinct().ToList().ForEach(a => {
Attachment item = new Attachment(a);
mail.Attachments.Add(item);
//item.Dispose();
});
}
这里添加了附件但是并没有释放资源
解决方案
smtp.Send(mail);
//mail.Attachments.Dispose();
//mail.Attachments[0].Dispose();
//mail.Dispose();
在 smtp.Send(mail); 执行语句之后,发送邮件完毕之后释放资源,注释的三行代码都可以使用,销毁
mail.Attachments[0].Dispose(); 销毁附件中的某一个附件占用
mail.Attachments.Dispose(); 销毁所有附件
mail.Dispose(); 销毁邮件对象
可以根据自己的需要使用对应销毁方式
总结
自己代码不规范,就是再写bug