【问题标题】:Error deleting a text file from a folder [closed]从文件夹中删除文本文件时出错[关闭]
【发布时间】:2014-07-25 13:27:15
【问题描述】:

我正在开发一个 C# 应用程序,它创建一个包含一些数据的文本文件,将其保存在文件夹中,将其发送到电子邮件地址列表并从该位置删除文件,但是当我调用 File.Delete () 它抛出一个异常,说文件不能被访问,因为它正在被另一个进程使用。那是因为电子邮件服务正在使用该文件并试图删除它,这是一个明显的异常,但是当我尝试在两个函数调用之间进行延迟时,它仍然给我一个异常

  _dailyBargainReport.sendRejectionReport(servername, fromAddress, password, sub, bodyofmail, rejectionReportPath);

             Task.Delay(20000);
            File.Delete(rejectionReportPath);

【问题讨论】:

  • 我将假设 sendRejectionReport 中没有 using 语句。实现 IDisposable 的所有内容都需要包装在 using 语句中。
  • .sendRejectionReport 看起来像什么?是异步的吗?
  • 请显示您用于创建文件的代码
  • 附带说明,您的Task.Delay 没有帮助,因为您没有在等待任务。要么这样做await Task.Delay(2000),要么干脆阻塞线程Thread.Sleep(2000)
  • 这个无所不在的 sendRejectionReport 方法是什么?如果您不调用该方法,文件删除是否仍然失败(即,问题真的与调用 sendRejectionReport 相关,还是可能发生其他事情)?

标签: c# file


【解决方案1】:

我认为您的问题是您没有在 FileStream 上调用 Dispose 方法

using (FileStream f = File.Open("example.txt", FileMode.Open, FileAccess.Read, FileShare.None))
{
    //do your operations
}
File.Delete(rejectionReportPath);

using statment 总是调用Dispose 所以相当于

try{
   FileStream f = File.Open("example.txt", FileMode.Open, FileAccess.Read, FileShare.None);
}
finally{
   ((IDisposable)f).Dispose();
}
//delete file here

更新

尝试这样等待函数

Task.Factory.StartNew(() =>
    {
        _dailyBargainReport.sendRejectionReport(servername, fromAddress, password, sub, bodyofmail, rejectionReportPath);
    })
    .ContinueWith(() =>
    {
        File.Delete(rejectionReportPath);
    }).Wait();

这样你就确定Delete函数在sendRejectionReport结束后被调用。
记得在sendRejectionReport函数中调用Dispose

【讨论】:

  • 不是因为文件被打开了而是因为文件被sendRejectionReport函数使用了
  • 我已经更新了答案
  • 使用更新后的新答案,既不发送邮件也不删除文件
  • 你在调试代码吗?你的函数被调用了吗?
  • 是的,我正在调试代码和函数并正确调用
【解决方案2】:

创建文件时,您可以创建一个标志,以便在进程关闭时删除。见:https://stackoverflow.com/a/400433/3846861

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多