当我尝试删除“foreach”循环中的文件时,我收到了错误消息。
我知道我需要在某个地方使用关键字'using`,但我不知道在哪里以及如何。
private void btnEmailIntegrationFiles_Click(object sender, EventArgs e)
{
DialogResult EmailWarningMsg = MessageBox.Show("You're about to email the Integration IAT text files. Are you sure?", "WARNING!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
if (EmailWarningMsg == DialogResult.Yes)
{
if (Directory.GetFiles(AppVars.NetworkIntegrationFileLocation).Length == 0)
{
MessageBox.Show("The folder is empty. Please create the files before sending it.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (Directory.GetFiles(AppVars.NetworkIntegrationFileLocation).Length != 4)
{
MessageBox.Show("The folder does not contain exactly 4 files.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
Email email = new Email();
email.SendEmailToFinalDestinationWithAttachments(AppVars.DBTeamEmail, AppVars.ChrisWhitmoreEmail, AppVars.DBTeamEmail, "Integration Files", "Please see integration files attached.");
}
}
PopulateListViewWithPoliciesAvailableToHoldBack();
string[] files = Directory.GetFiles(AppVars.NetworkIntegrationFileLocation);
foreach (string file in files)
{
File.Delete(file);
}
}
}
如何使用关键字using
进行“电子邮件发送”,以便在尝试删除以附件形式通过电子邮件发送的文件时,我不会遇到此错误消息?
这是发送电子邮件类:
public void SendEmailToFinalDestinationWithAttachments(string EmailFrom, string EmailTo, string EmailCC, string EmailSubject, string EmailBody)
{
try
{
MailMessage EmailMessage = new MailMessage();
SmtpClient smtp = new SmtpClient(AppVars.SMTPClient, AppVars.SMTPClientPort);
smtp.UseDefaultCredentials = false;
EmailMessage.IsBodyHtml = true;
EmailMessage.To.Add(EmailTo);
EmailMessage.CC.Add(EmailCC);
EmailMessage.CC.Add(user);
EmailMessage.Subject = EmailSubject;
EmailMessage.From = new MailAddress(EmailFrom);
EmailMessage.Body = EmailBody;
string[] files = Directory.GetFiles(AppVars.NetworkIntegrationFileLocation, "*" + DateTime.Now.ToString("yyyyMMdd") + "*");
foreach (string file in files)
{
EmailMessage.Attachments.Add(new Attachment(file));
}
smtp.Send(EmailMessage);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
答案 0 :(得分:2)
您需要将您的EMail类修改为:
using (MailMessage EmailMessage = new MailMessage()) {
...
smtp.Send(EmailMessage);
}