Cannot create a file when that file already exists when using Directory.Move

后端 未结 5 930
我寻月下人不归
我寻月下人不归 2020-12-17 08:59

I am trying to move the directory from one location to another location on the same drive. I am getting \"Cannot create a file when that file already exists

5条回答
  •  生来不讨喜
    2020-12-17 09:42

    As per MSDN,

    This method throws an IOException if, for example, you try to move c:\mydir to c:\public, and c:\public already exists.

    But, in your method, you are creating the destination directory before you move.

    So, you need to change your method from

    if (Directory.Exists(destinationdirectory))
    {
      Directory.Move(sourcedirectory, destinationdirectory);
    }
    else
    {
      Directory.CreateDirectory(destinationdirectory);
      Directory.Move(sourcedirectory, destinationdirectory);
    }
    

    to

    if (Directory.Exists(destinationdirectory))
    {
      //delete or rename
    }
    Directory.Move(sourcedirectory, destinationdirectory);
    

提交回复
热议问题