2012-10-25 107 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。这应该释放文件资源并允许您将其复制。