【问题标题】:C# - Unable to delete a file after copying and overwrittingC# - 复制和覆盖后无法删除文件
【发布时间】:2017-09-30 08:18:31
【问题描述】:

我正在开发一个应用程序,它将所有文本文件的路径从一个文件夹读取到一个列表中。它读取每个文件,创建一个临时输出文件,用临时输出文件覆盖原始文件并删除临时输出文件。

以下是我的代码:

    foreach (string lF in multipleFiles)
    {
        int lineNumber = 0;
        using (StreamReader sr = new StreamReader(lF))
        {
            using (StreamWriter sw = new StreamWriter(lF + "Output"))
            {
                while (!sr.EndOfStream)
                {

                    //LOGIC

                    sw.WriteLine(line);
                }
            }
        }
        File.Copy(lF + "Output", lF, true);
        //File.Delete(lF + "Output");
        try
        {

            File.Delete(lF + "Output"); <--- ERROR HERE
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

由于以下错误,我无法删除临时输出文件:

{"进程无法访问文件'',因为它正在 被另一个进程使用。"}

错误不会发生在每个文件上,而只会发生在少数文件上。没有任何文件被打开或被任何其他应用程序使用。

如何删除临时文件?

更新:参考Does FileStream.Dispose close the file immediately?

在 File.Delete() 之前添加了 Thread.Sleep(1),问题依然存在。尝试将睡眠值增加到 5。没有运气。

【问题讨论】:

  • @someone 我尝试添加 Thread.Sleep(1)。错误仍然发生。我什至尝试将睡眠值增加到 5。
  • 50 或 500 怎么样? 1 或 5 毫秒不算多。
  • @someone 它似乎工作。雷内的回答也是如此。感谢您为我指明正确的方向。我不知道 bitlocker 或防病毒软件会对它产生影响。

标签: c#


【解决方案1】:

您总是冒着病毒扫描程序或堆栈中的某些其他驱动程序仍然保留该文件或其目录条目的风险。使用一些重试机制,但这仍然不能保证您能够删除该文件,因为文件操作不是原子的,因此任何进程都可以在您尝试删除它的调用之间打开该文件。

var path = lf + "Output";
// we iterate a couple of times (10 in this case, increase if needed)
for(var i=0; i < 10; i++) 
{
    try 
    {
        File.Delete(path);
        // this is success, so break out of the loop
        break;
    } catch (Exception exc) 
    {
         Trace.WriteLine("failed delete #{0} with error {1}", i, exc.Message);
         // allow other waiting threads do some work first
         // http://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/
         Thread.Sleep(0);
         // we don't throw, we just iterate again
    }
}
if (File.Exists(path)) 
{
    // deletion still not happened
    // this is beyond the code can handle
    // possible options:
    // store the filepath to be deleted on startup
    // throw an exception
    // format the disk (only joking)
}

代码稍微改编自我的answer here,但那是在不同的上下文中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2012-02-05
    • 2021-12-02
    • 2012-04-13
    • 2013-01-24
    相关资源
    最近更新 更多