繁体   English   中英

文件被另一个进程异常C#使用

[英]File is used by another process exception C#

我创建了一个应用程序,该应用程序从数据库中的信息生成excel文件。 这些文件保存在我的硬盘上的一个文件夹中。

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

我的问题是,当我生成一批文件然后发送它们时,我想生成另一批文件,我无法删除其中一个旧文件,因为邮寄方法仍然保留其中一个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("system@lol.dk");
        msg.To.Add(new MailAddress("lmy@lol.dk"));
        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);
    }
}

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

谁能帮我这个?

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("system@lol.dk");
          msg.To.Add(new MailAddress("lmy@lol.dk"));
          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);
        }
     }

听起来您在生成excel文件时可能没有关闭文件流,或者在尝试通过电子邮件发送它们时在excel中打开了它们。

请您显示用于生成excel文件的代码。

您需要处理附件对象。 使用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("system@lol.dk");
        msg.To.Add(new MailAddress("lmy@lol.dk"));
        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());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM