Mimic File.Move if the destination already exists

前端 未结 5 1837
小鲜肉
小鲜肉 2020-12-20 17:48

From the documentation of File.Move:

Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an IOEx

5条回答
  •  别那么骄傲
    2020-12-20 18:01

    It is difficult to simulate an atomic operation if the operating system doesn't give you good atomic operations. Move is atomic on some but not all filesystems, but not when you are moving disk to disk.

    In case of the same disk, Delete + Move is somewhat elegant (fast and safe) as it does not really stuffle the data in any way. You could further extend it to

    try
    {
        Move(dest, tmp);
        Move(src, dest);
        Delete(tmp);
    }
    catch
    {
        try
        {
            Move(tmp, dest);
        }
        catch
        {
        }
        throw;
    }
    

    (This makes it less likely that you will lose the destination file when you for example do not have the rights necessary to finish the move.)

    In a scenario where you do not know that it is the same disk, your solution is safe enough and simple enough. However, it copies the data even within the same disk, bringing you a wider window of risk of a power failure.

提交回复
热议问题