2

我目前正在调试我的代码,因为它给了我一个错误:

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 等,但我如何在我的代码中使用它?提前致谢。

4

2 回答 2

4

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

于 2015-09-05T04:03:22.553 回答
1
using(FileStream stream = new FileStream("thepath"))
{
      //do stuff with the file
      stream .Close();
}

现在流将被关闭和处理。

于 2015-09-05T03:16:27.507 回答