I\'ve got a folder:
c:\\test
I\'m trying this code:
File.Move(@\"c:\\test\\SomeFile.txt\", @\"c:\\test\\Test\");
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.
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.
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... ;)