.NET拒绝访问目录复制操作后操作、目录、NET

2023-09-07 09:33:19 作者:三分靠运气七分靠打拼

我在另一个目录执行目录的一个安全的副本如下:

I'm performing a "safe" copy of a directory over another directory as follows:

由于源C:\源和目标C:\目标

Given the source C:\Source and target C:\Target

复制C:\来源为C:\目标-传入 将C:\目标(如果存在)到C:\目标-传出 将C:\目标,传入到C:\目标 删除C:\目标,即将离任的(如果存在的话)

如果任前三个步骤的失败,我会尝试把东西回来,因为他们以prevent数据丢失。

If any of the first three steps fail, I'll attempt to put things back as they were to prevent data loss.

不过,C的举动:\目标,传入到C:\目标失败,访问路径C:\目标,来电被拒绝的大部分时间。

However, the move of C:\Target-incoming to C:\Target fails with "Access to the path C:\Target-incoming is denied" most of the time.

目前,插入Thread.sleep代码(100)的移动操作解决了这个问题,我之前。然而,在等待第二.1似乎是可笑的我。 Thread.sleep代码(10)是不够的解决它。我也有下沉的感觉,价值我必须等待依赖于磁盘IO速度。

At the moment, inserting Thread.Sleep(100) just before the move operation fixes the problem for me. However, waiting .1 of a second seems ridiculous to me. Thread.Sleep(10) isn't enough to fix it. I also have the sinking feeling that the value I have to wait depends on the speed of disk IO.

所以,我的问题:

我可以prevent这种情况的发生? 如果没有,有没有找出当上了目录的锁被释放复制后?的方法

编辑:为了清楚起见,我做的所有这些操作在一个方法上的一个线程,我只是用Thread.sleep()方法来暂停code流了一会儿。这些举措和副本正在做标准.NET Directory.Move(),Directory.CreateDirectory()和File.CopyTo()方法。这样看来,在.NET方法之前在各文件上的锁返回被释放,导致有必要等待一定量的时间,然后继续。

For clarity, I'm doing all these operations in one method on one thread, and I'm just using Thread.Sleep() to pause code flow for a moment. The moves and copies are being done with standard .NET Directory.Move(), Directory.CreateDirectory() and File.CopyTo() methods. It would appear that the .NET methods are returning before the locks on the respective files are being released, causing the necessity to wait an amount of time before continuing.

推荐答案

一堆的测试后,似乎试图将锁定的文件夹获取OS快点解除锁定的非常行为,即使第一次尝试失败。

After a bunch of testing, it seems like the very act of trying to move a locked folder gets the OS to hurry up and release the lock, even if the first attempt fails.

我写了这个扩展方法DirectoryInfo的:

I wrote this extension method to DirectoryInfo:

public static void TryToMoveTo(this DirectoryInfo o, string targetPath) {

    int attemptsRemaining = 5;

    while (true) {
        try {
            o.MoveTo(targetPath);
            break;

        } catch (Exception) {

            if (attemptsRemaining == 0) {
                throw;
            } else {
                attemptsRemaining--;
                System.Threading.Thread.Sleep(10);
            }
        }
    }
}

在调试原来的问题,我定居在等候100毫秒的东西少似乎导致异常(我试过10,25,50,75和100毫秒)。然而,在上面的方法,我等待10ms的重试之前,我从来没有,永远的有超过一个例外扔在我的每个几百个测试运行。

While debugging the original problem, I settled on waiting for 100ms as anything less seemed to cause exceptions (I tried 10, 25, 50, 75 and 100ms). However, in the method above I wait 10ms before retrying, and I never, ever got more than one exception thrown in each of my hundreds of test runs.