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.
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.
if (!File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
}
or
if (File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Delete(@"c:\test\Test\SomeFile.txt");
}
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
This will either:
If the file doesn't exist at the destination location, successfully move the file, or;
If the file does exist at the destination location, delete it, then move the file.
Edit: I should clarify my answer, even though it's the most upvoted!
The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires.
So, your second parameter should be c:\test\Test\SomeFile.txt.
Personally I prefer this method.
This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.
Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.
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:
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... ;)
With C# on .Net Core 3.0 and beyond, there is now a third boolean parameter:
In .NET Core 3.0 and later versions, you can call Move(String, String, Boolean) setting the parameter overwrite to true, which will replace the file if it exists.
For all other versions of .Net, this answer is the best. Copy with Overwrite, then delete the source file. This is better because it makes it an atomic operation. (I have attempted to update the MS Docs with this)