C#使用MailMessage发附件再修改文件正由另一进城使用错误解决办法
C#使用MailMessage发送附件时,如果没有释放附件资源占用,再次修改附件内容会报错
文件“x:\xxxxxxxxx"正由另外一进程使用,因此该进程无法访问该文件。
删除文件会提示操作无法完成,因为文件已在IIS Worker Process中打开。
添加附件的代码如下
if (UserCheck.IsNotNull(attachment)) { string ext = ""; string[] attachments = attachment.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (string f in attachments) if (f.Trim() != "" && File.Exists(HttpContext.Current.Server.MapPath("~/attachments/" + f))) mail.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath("~/attachments/" + f))); }
解决办法就是要在SmtpClient发送邮件后释放附件资源,否则IIS会一直占用附件,无法再次修改或者删除,除非IIS程序池重启。
SmtpClient client = new SmtpClient(smtpserver); if (smtpserver == "smtp.qq.com") client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(fromMail, password); try { client.Send(mail); } catch (System.Net.Mail.SmtpException ex) { return ex.Message + "|" + fromMail; } mail.Attachments.Dispose();//释放资源,要不附件会一直被占用无法修改文件
如果你是通过下面的对象添加的附件
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); disposition.ReadDate = System.IO.File.GetLastAccessTime(file); // Add the file attachment to this e-mail message. //这里添加附件 message.Attachments.Add(data);
需要用data.Dispose(); 释放资源,而不是mail.Attachments.Dispose();
//这里才是释放附件解除锁定的地方,而网上大多数是说使用message.Attachments.Dispose(),但我试了就是不能解除锁定 data.Dispose();
加支付宝好友偷能量挖...
原创文章,转载请注明出处:C#使用MailMessage发附件再修改文件正由另一进城使用错误解决办法