2015-10-29 49 views
-2

在我的網站上,用戶從他的系統上傳一些文件併發送電子郵件。如何在asp.net C#中發送電子郵件後刪除附件?

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); 
} 

但是,如果電子郵件sendings失敗,那麼我可以刪除該文件,但如果郵件成功發送,然後我得到一個異常

文件檢驗.pdf不能被刪除,因爲它由另一個進程使用

是否可以附加文件而不保存它?

如果不是,那麼在發送電子郵件後如何刪除文件?

供參考: - 這是一個AJAX調用。

+0

的問題是不你顯示的代碼。顯示電子郵件發送和文件刪除代碼。 – CodeCaster

+0

finally {System.IO.File.Delete(attachmentLocation);} – abc

+0

請修改代碼添加到您的文章 - 通常很難閱讀評論 –

回答

0

我覺得這兩個解決方案可以在第一個鏈接,我認爲使用的一個是解決你的問題

「爲了解決這個問題,基本上你需要調用Dispose ()MailMessage對象(其中將那麼Attachment對象的調用Dispose (),從而釋放文件上的鎖,並允許你刪除它)

有兩個明顯的方式來做到這一點。

1)傳遞MailMessage對象SendAsync() ,通過UserToken參數。然後,在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

1

可以實現它全無保存文件

using (var stream = new MemoryStream()) 
using (var writer = new StreamWriter(stream))  
using (var mailClient = new SmtpClient("localhost", 25)) 
using (var message = new MailMessage("[email protected]", "[email protected]", "Just testing", "See attachment...")) 
{ 
    writer.Flush(); 
    stream.Position = 0;  

    message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv")); 

    mailClient.Send(message); 
} 

而現在你只需要從文件中獲取memorystrem

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