【问题标题】:How do I delete the attachment after email is sent in asp.net C#? [closed]在asp.net C#中发送电子邮件后如何删除附件? [关闭]
【发布时间】:2016-01-29 16:04:48
【问题描述】:

在我的网站中,用户从他的系统上传一些文件并发送电子邮件。

try
{
  if(Request.Files!=null)
  {
     //save the file to some temp location 
     //Attach the file to email & send
  }
}
catch(Exception ex)
{
  //log exception
}
finally
{
    //delete the file from temp location
    System.IO.File.Delete(attachmentLocation);
}

但是如果电子邮件发送失败,那么我可以删除文件,但如果电子邮件发送成功,则会出现异常

文件 test.pdf 不能被删除,因为它被另一个进程使用了​​

是否可以在不保存的情况下附加文件?

如果不能,那么在发送电子邮件后如何删除文件?

仅供参考:- 这是一个 AJAX 调用。

【问题讨论】:

  • 问题不在于您显示的代码。显示邮件发送和文件删除代码。
  • 最后 { System.IO.File.Delete(attachmentLocation);}
  • 请在您的帖子中编辑代码添加 - 在评论中通常很难阅读
  • 现在检查..sn-p

标签: c# asp.net email email-attachments


【解决方案1】:

我认为这两个解决方案中的一个可以使用第一个链接中的我认为是您问题的解决方案

"要解决这个问题,基本上你需要在MailMessage对象上调用Dispose ( )(其中会在Attachment对象上调用Dispose ( ),从而释放文件上的锁,并允许你删除它)。

有两种明显的方法可以做到这一点:

1) 通过 UserToken 参数将 MailMessage 对象传递给 SendAsync () 。然后,在 SendCompletedCallback 方法中,强制转换为 MailMessage e.UserState 类型,并在其上调用 Dispose ( )

http://www.dreamincode.net/forums/topic/325303-c%23how-to-delete-attach-file-after-send-mail/

http://www.codeproject.com/Questions/360228/how-to-delete-attachment-file-after-it-is-send-as

【讨论】:

    【解决方案2】:

    您可以通过我们的保存文件来实现它

    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))    
    using (var mailClient = new SmtpClient("localhost", 25))
    using (var message = new MailMessage("me@example.com", "you@example.com", "Just testing", "See attachment..."))
    {
        writer.Flush();
        stream.Position = 0;     
    
        message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));
    
        mailClient.Send(message);
    }
    

    现在你只需要从你的文件中获取记忆流

    var postedFile = httpRequest.Files[0];
    using (var binaryReader = new BinaryReader(postedFile.InputStream))
    {
       var zz = new MemoryStream(binaryReader.ReadBytes(postedFile.ContentLength));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 2013-08-22
      • 1970-01-01
      • 2013-04-25
      相关资源
      最近更新 更多