I've got a folder:
c:\test
I'm trying this code:
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test");
I get exception:
File already exists
The output directory definitely exists and the input file is there.
This error has the following causes and solutions: This error occurs at run time when the new file name, for example, one specified in a Name statement, is identical to a file name that already exists. Specify a new file name in the Name statement or delete the old file before specifying it in a Name statement.
File. Move() doesn't support overwriting of an existing file. In fact, it will throw an IOException if a file with the same path as sourceDestFilename already exists.
This is because you're trying to fake the existence of the Backup folder (so it must not exist already), but you also need its parents to exist. Windows will hence create a hard link shortcut Backup on the C:\ drive.
Move() is an inbuilt File class method that is used to move a specified file to a new location. This method also provides the option to specify a new file name. Syntax: public static void Move (string sourceFileName, string destFileName);
What you need is:
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:
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With