C#:IIS(发送电子邮件)阻止文件访问

时间:2013-11-13 11:07:44

标签: c# email iis

我在使用C#发送带附件的电子邮件时遇到问题。 第一次一切正常:生成pdf文件并附加到电子邮件,电子邮件可以发送和接收。 但是,如果我尝试两次,生成文件时会出现IO异常。 如果我尝试手动重命名该文件,我会收到一条错误消息,告诉我IIS工作进程继续使用该文件。

如果我评论了发送电子邮件的部分,则可以生成并保存更多次文件。 因此,确定错误出现在此代码部分中。

以下是我发送电子邮件的代码:

MailMessage eMail = new MailMessage();
eMail.To.Add(sEmailAddressReceiver); //filled before
eMail.From = new MailAddress(sEmailAddressSender); //filled before
eMail.Subject = "Title";
eMail.Priority = MailPriority.Normal;
eMail.Body = "File is attached.";
Attachment aAttachment = new Attachment(sFilename);
eMail.Attachments.Add(aAttachment);
SmtpClient smtpClient = new SmtpClient("xxx", 25);
smtpClient.Send(eMail);

有人知道缺少什么吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

对于初学者,尝试在一次性物品上使用Dispose()

您可以使用using语句隐式执行此操作。 或者通过明确调用Dispose()

        using (MailMessage eMail = new MailMessage())
        {
            eMail.To.Add(sEmailAddressReceiver); //filled before
            eMail.From = new MailAddress(sEmailAddressSender); //filled before
            eMail.Subject = "Title";
            eMail.Priority = MailPriority.Normal;
            eMail.Body = "File is attached.";

            using (Attachment aAttachment = new Attachment(sFilename))
            {
                eMail.Attachments.Add(aAttachment);
                using (SmtpClient smtpClient = new SmtpClient("xxx", 25))
                {
                    smtpClient.Send(eMail);
                }
            }
        }
相关问题