File.Move Does Not Work - File Already Exists

前端 未结 9 1131
无人及你
无人及你 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:30

    You need to move it to another file (rather than a folder), this can also be used to rename.

    Move:

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

    Rename:

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

    The reason it says "File already exists" in your example, is because C:\test\Test tries to create a file Test without an extension, but cannot do so as a folder already exists with the same name.

    0 讨论(0)
  • 2020-12-04 12:34

    According to the docs for File.Move there is no "overwrite if exists" parameter. You tried to specify the destination folder, but you have to give the full file specification.

    Reading the docs again ("providing the option to specify a new file name"), I think, adding a backslash to the destination folder spec may work.

    0 讨论(0)
  • 2020-12-04 12:40

    If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:

    string newFileLocation = @"c:\test\Test\SomeFile.txt";
    
    while (File.Exists(newFileLocation)) {
        newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
    }
    File.Move(@"c:\test\SomeFile.txt", newFileLocation);
    

    This assumes the only '.' in the file name is before the extension. It splits the file in two before the extension, attaches "_copy." in between. This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)

    0 讨论(0)
提交回复
热议问题