2013-03-21 93 views
0

我已经创建了一个应用程序,可以根据数据库中的信息生成excel文件。这些文件保存在我的硬盘上的文件夹中。文件被另一个进程异常使用C#

之后我附加文件并通过邮件发送。当我生成另一批文件时,我删除旧文件,然后创建新文件。

我的问题是,当我生成一批文件,然后发送它们,我想生成另一批我不能删除其中一个旧文件,因为邮寄方法仍然坚持一个Excel文件。

这里是我的代码:

public void SendMailedFilesDKLol() { 
    string[] sentFiles=Directory.GetFiles(some_Folder); 

    if(sentFiles.Count()>0) { 
     System.Net.Mail.SmtpClient client=new System.Net.Mail.SmtpClient("ares"); 
     System.Net.Mail.MailMessage msg=new System.Net.Mail.MailMessage(); 

     msg.From=new MailAddress("[email protected]"); 
     msg.To.Add(new MailAddress("[email protected]")); 
     msg.Subject="IBM PUDO"; 

     msg.Body= 
      sentFiles.Count()+" attached file(s) has been sent to the customer(s) in question "; 

     msg.IsBodyHtml=true; 

     foreach(string file in sentFiles) { 
      Attachment attachment=new Attachment(file); 
      msg.Attachments.Add(attachment); 
     } 

     client.Send(msg); 
    } 
} 

我试图处理客户端元素,但没有帮助。

任何人都可以帮助我吗?

+0

您确定这是您的邮件代码,而不是Excel过程谁持有您的文档? – LaGrandMere 2013-03-21 08:31:24

+0

是的,因为当我注释掉邮件发送方法,我可以重新生成文件,因为我想 – Lahib 2013-03-21 08:46:26

回答

3

两个System.Net.Mail.MailMessage & System.Net.Mail.SmtpClient是IDisposable的类。您可以尝试以下操作:

using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("ares")) 
    { 
     using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage()) 
     { 
      msg.From = new MailAddress("[email protected]"); 
      msg.To.Add(new MailAddress("[email protected]")); 
      msg.Subject = "IBM PUDO"; 
      msg.Body = sentFiles.Count() + " attached file(s) has been sent to the customer(s) in question "; 
      msg.IsBodyHtml = true; 
      foreach (string file in sentFiles) 
      { 
       Attachment attachment = new Attachment(file); 
       msg.Attachments.Add(attachment); 
      } 

      client.Send(msg); 
     } 
    } 
0

听起来好像你可能没有在生成excel文件时关闭你的文件流,或者你试图通过电子邮件发送它们在Excel中打开它们。

请你可以显示你的代码来生成excel文件。

0

您需要处置附件对象。 实施例使用LINQ:

public void SendMailedFilesDKLol() { 
    string[] sentFiles=Directory.GetFiles(some_Folder); 

    if(sentFiles.Count()>0) { 
     System.Net.Mail.SmtpClient client=new System.Net.Mail.SmtpClient("ares"); 
     System.Net.Mail.MailMessage msg=new System.Net.Mail.MailMessage(); 

     msg.From=new MailAddress("[email protected]"); 
     msg.To.Add(new MailAddress("[email protected]")); 
     msg.Subject="IBM PUDO"; 

     msg.Body= 
      sentFiles.Count()+" attached file(s) has been sent to the customer(s) in question "; 

     msg.IsBodyHtml=true; 

     var attachments = sentFiles.Select(f => new Attachment(f)).ToList(); 

     attachments.ForEach(a => msg.Attachments.Add(a)); 

     client.Send(msg); 

     attachments.ForEach(a => a.Dispose()); 
    } 
} 
相关问题