Directory.Move doesn't work (file already exist)

后端 未结 6 579
逝去的感伤
逝去的感伤 2020-11-30 06:42

I\'ve got main folder:

c:\\test

And there I have 2 folders: Movies and Photos.

Photos has three folders with files with the same s

6条回答
  •  爱一瞬间的悲伤
    2020-11-30 07:27

    The most common 2 reasons why Directory.Move could fail are, if:

    • It's a different volume (you need to Copy/Delete)
    • It already exists (doesn't support overwrite by default)

    Here is my simple solution for the second problem (overwrite):

    public bool MoveDirectory(string sourceDirName, string destDirName, bool overwrite)
    {
        if (overwrite && Directory.Exists(destDirName))
        {
            var needRestore = false;
            var tmpDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            try
            {
                Directory.Move(destDirName, tmpDir);
                needRestore = true; // only if fails
                Directory.Move(sourceDirName, destDirName);
                return true;
            }
            catch (Exception)
            {
                if (needRestore)
                {
                    Directory.Move(tmpDir, destDirName);
                }
            }
            finally
            {
                Directory.Delete(tmpDir, true);
            }
        }
        else
        {
            Directory.Move(sourceDirName, destDirName); // Can throw an Exception
            return true;
        }
        return false;
    }
    

提交回复
热议问题