2012-10-25 113 views
3

我有以下代碼,基本上附加到一個電子郵件文件的文件然後附加所有附件和電子郵件發送後,我嘗試刪除所有文件,但是我得到一個文件使用異常。我相信,錯誤出現在這條線發送電子郵件附件後刪除c#文件

Attachment data = new Attachment(file, MediaTypeNames.Application.Octet); 

我使用此代碼嘗試,但我得到一個不能發送電子郵件

using Attachment data = new Attachment(file, MediaTypeNames.Application.Octet)){ 
//and the rest of the code in here. 

} 


foreach (KeyValuePair<string, string> kvp in reports) { 
    browser.GoTo(kvp.Value); 
    Thread.Sleep(1000); 

    System.IO.File.Move(@"C:\Reports\bidata.csv", @"C:\Reports\"+kvp.Key.ToString()+".csv"); 

    string file = @"C:\Reports\" + kvp.Key.ToString() + ".csv"; 

    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. 

    mail.Attachments.Add(data); 
} 

smtpserver.Send(mail); 
string[] files = Directory.GetFiles(@"C:\Reports"); 
foreach (string files1 in files) 
{ 
    File.Delete(files1); 
} 

回答

5

爲了首先刪除文件,您必須處理附件和郵件對象,然後刪除文件

2

,將其置於一個usings或打電話直接處理處置的smtpclient。這應該釋放文件資源並允許您將其複製。