Reputation: 629
I have the following code which copies a file to a specific folder and then renames it. When a file with that name already exists I get the following exception:
Cannot create a file when that file already exists
Is there a way to overwrite the file and rename it? or I should delete the old one and then change the name?
Here is my code:
File.Copy(FileLocation, NewFileLocation, true);
//Rename:
File.Move(Path.Combine(NewFileLocation, fileName), Path.Combine(NewFileLocation, "File.txt"));
Upvotes: 11
Views: 97237
Reputation: 325
I always use MoveFileEx with the flag MOVEFILE_REPLACE_EXISTING.
Limitations:
It needs to use PInvoke, so it means your code will only work on the Windows platform.
This flag MOVEFILE_REPLACE_EXISTING only work with File(Doesn't work with Folder)
If lpNewFileName or lpExistingFileName name a directory and lpExistingFileName exists, an error is reported.
Upvotes: -1
Reputation: 26209
Step 1 : as a first step identify wether the file exists or not before copying the file.
using File.Exists()
method
Step 2: if the file already exists with same name then delete the existing file using File.Delete()
method
Step 3: now copy the File into the new Location using File.Copy()
method.
Step 4: Rename the newly copied file.
Try This:
string NewFilePath = Path.Combine(NewFileLocation, fileName);
if(File.Exists(NewFilePath))
{
File.Delete(NewFilePath);
}
//Now copy the file first
File.Copy(FileLocation, NewFileLocation, true);
//Now Rename the File
File.Move(NewFilePath, Path.Combine(NewFileLocation, "File.txt"));
Upvotes: 2
Reputation: 2857
Try to use only:
if (File.Exists("newfilename"))
{
System.IO.File.Delete("newfilename");
}
System.IO.File.Move("oldfilename", "newfilename");
Upvotes: 29
Reputation: 101604
You're correct, File.Move
will throw an IOException
if/when the filename already exists. So, to overcome that you can perform a quick check before the move. e.g.
if (File.Exists(destinationFilename))
{
File.Delete(destinationFilename);
}
File.Move(sourceFilename, destinationFilename);
Upvotes: 6
Reputation: 70718
You should use File.Exists
rather than letting the Exception throw. You can then handle if the file should be overwrote or renamed.
Upvotes: 4
Reputation: 10430
One simple option is to delete the file if it exists:
if (System.IO.File.Exists(newFile)) System.IO.File.Delete(newFile);
System.IO.File.Move(oldFile, newFile);
Something like that should work.
Upvotes: 8