【问题标题】:Deleting files gives an error (The process cannot access the file..)删除文件时出错(进程无法访问文件..)
【发布时间】: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() 在此调用之后。试着把它放在这个调用之前,看看它是否可以删除文件。
  • 因为邮件发送成功。

标签: c# system.io.directory


【解决方案1】:

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

【讨论】:

  • 太棒了!我很高兴能帮上忙。
  • 很好,对我的问题也有帮助
【解决方案2】:
using(FileStream stream = new FileStream("thepath"))
{
      //do stuff with the file
      stream .Close();
}

现在流将被关闭和处置。

【讨论】:

  • 末尾的stream.Close()是多余的
  • @BroSlow 怀疑是这样,但我没有测试所以我添加了它以确保
  • 在 using 语句的末尾不需要使用 stream.close。 using 语句会为您处理它。
  • 感谢您的回答,但这不是我使用的代码。
  • stream.Close 在 using 块中是多余的
猜你喜欢
  • 1970-01-01
  • 2012-01-29
  • 2011-06-22
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
相关资源
最近更新 更多