File.Move Does Not Work - File Already Exists

前端 未结 9 1228
无人及你
无人及你 2020-12-04 12:08

I\'ve got a folder:

c:\\test

I\'m trying this code:

File.Move(@\"c:\\test\\SomeFile.txt\", @\"c:\\test\\Test\");         


        
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 12:27

    You can do a P/Invoke to MoveFileEx() - pass 11 for flags (MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
    static extern bool MoveFileEx(string existingFileName, string newFileName, int flags);
    

    Or, you can just call

    Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(existingFileName, newFileName, true);
    

    after adding Microsoft.VisualBasic as a reference.

提交回复
热议问题