C# 无法删除文件,因为它是';正在被另一个进程使用
当我试图删除“foreach”循环中的文件时,我在最后收到了错误消息 我知道我需要在某处使用关键字“using”,但我不确定在哪里以及如何使用C# 无法删除文件,因为它是';正在被另一个进程使用,c#,process,using,C#,Process,Using,当我试图删除“foreach”循环中的文件时,我在最后收到了错误消息 我知道我需要在某处使用关键字“using”,但我不确定在哪里以及如何使用 private void btnEmailIntegrationFiles_Click(object sender, EventArgs e) { DialogResult EmailWarningMsg = MessageBox.Show("You're about to email the Integration IAT text files
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);
}
}
}
我如何使用关键字使用发送“电子邮件”,以便在尝试删除作为附件发送的文件时不会遇到此错误消息
以下是发送电子邮件类:
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);
}
}
您需要修改电子邮件类,使其类似于:
using (MailMessage EmailMessage = new MailMessage()) {
...
smtp.Send(EmailMessage);
}
可能是通过电子邮件;但是,您还没有提供有关该类的任何详细信息。它是从哪里来的?SendEmailToFinalDestinationWithAttachments做什么,等等?清理代码/重构代码,并确保发布符合问题的所有必要代码。提供了email类。我很确定问题出在“string[]files=Directory.GetFiles(AppVars.NetworkIntegrationFileLocation)”+DateTime.Now.ToString(“yyyyMMdd”)+”;foreach(文件中的字符串文件){EmailMessage.Attachments.Add(新附件(文件));}”…我该如何在这里使用关键字“using”?这不是你问题的原因,但你到底为什么一直重复目录读取?最后一个实际上是危险的——如果其他东西被扔在中间,它就会被盲目地杀死。你说得对。我应该只删除应该在那里出现的文件。。。虽然该文件夹中不应该有其他内容。。。