Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename existing file name

Tags:

c#

.net

file-io

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"));               
like image 912
user1016179 Avatar asked Feb 25 '14 13:02

user1016179


3 Answers

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);
like image 165
Brad Christie Avatar answered Sep 25 '22 08:09

Brad Christie


Try to use only:

if (File.Exists("newfilename"))
{
    System.IO.File.Delete("newfilename");
}

System.IO.File.Move("oldfilename", "newfilename");
like image 37
Only a Curious Mind Avatar answered Sep 24 '22 08:09

Only a Curious Mind


You should use File.Exists rather than letting the Exception throw. You can then handle if the file should be overwrote or renamed.

like image 31
Darren Avatar answered Sep 24 '22 08:09

Darren