【发布时间】:2015-09-05 12:10:19
【问题描述】:
我目前正在调试我的代码,因为它给了我一个错误:
The process cannot access the file because it is being used by another process.
我认为错误发生在这行代码中
foreach (var filename in filenames)
{
var file = Path.Combine(filePath, filename);
mail.Attachments.Add(new Attachment(file));
}
// Send Mail
smtpServer.Send(mail);
DeleteFiles();
我想在使用这种方法发送邮件时删除文件夹中的文件
private void DeleteFiles()
{
string filePath = Server.MapPath("~/Content/attachments");
Array.ForEach(Directory.GetFiles(filePath), System.IO.File.Delete);
}
我读到有关关闭/处置的信息? FileStream 等,但我如何在我的代码中使用它?提前致谢。
【问题讨论】:
-
是什么让您认为错误出在这些代码行中?您是否设置了断点并单步执行您的代码以查看它在哪里引发错误?
-
我认为您需要处理通过邮件发送的数据。可能是邮件服务器锁定了文件。
-
@StillLearnin 因为当我将 DeleteFiles() 放在 foreach 之前它正在工作但是当它放在 foreach 之后它给了我错误。
-
你怎么知道问题不是由 smtpServer.Send(mail) 引起的?您的代码显示 DeleteFiles() 在此调用之后。试着把它放在这个调用之前,看看它是否可以删除文件。
-
因为邮件发送成功。