我正在调试我的代码,因为它给了我一个错误:
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等等,但我如何在我的代码中使用它?提前谢谢。
答案 0 :(得分:3)
mail.dispose();
您应该在删除文件之前处理邮件。 应该删除文件上的锁定。
foreach (var filename in filenames)
{
var file = Path.Combine(filePath, filename);
mail.Attachments.Add(new Attachment(file));
}
// Send Mail
smtpServer.Send(mail);
mail.Dispose();
DeleteFiles();
https://msdn.microsoft.com/en-us/library/0w54a951(v=vs.110).aspx
答案 1 :(得分:1)
using(FileStream stream = new FileStream("thepath"))
{
//do stuff with the file
stream .Close();
}
现在流将被关闭并处理掉。