0

データベース内の情報からExcelファイルを生成するアプリケーションを作成しました。これらのファイルは、HDDのフォルダに保存されます。

その後、ファイルを添付してメールで送信します。別のファイルのバッチを生成するときは、古いファイルを削除してから、新しいファイルを作成します。

私の問題は、ファイルの1つのバッチを生成してから送信したときに、別のバッチを生成したいのですが、メール送信方法がまだExcelファイルの1つを保持しているため、古いファイルの1つを削除できません。

これが私のコードです:

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

クライアント要素を破棄しようとしましたが、役に立ちませんでした。

誰かがこれを手伝ってくれますか?

4

3 に答える 3

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("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);
        }
     }
于 2013-03-21T08:41:34.790 に答える
0

You need to dispose the Attachment objects. Example using 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());
    }
}
于 2013-03-21T08:39:31.557 に答える
0

Excelファイルを生成するときにファイルストリームを閉じていないか、電子メールで送信しようとしたときにExcelで開いているようです。

Excelファイルを生成するためのコードを教えてください。

于 2013-03-21T08:31:44.460 に答える