Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'File.Copy' does not overwrite a file

Tags:

c#

.net

Using the following code, I am trying to overwrite a file if it exists. Currenly it throws IOException. How can I fix this problem?

File.Copy(filePath, newPath);
like image 697
Captain Comic Avatar asked Oct 27 '10 16:10

Captain Comic


People also ask

How do I copy files without overwriting?

If you are copying files using drag-drop or copy/paste, you may simply choose “Skip this file” or “Skip these files” option to not overwrite the files that are already existed at the destination folder. Or, if you are using command line copy, you can answer N to bypass these files that are already existed.

How do I overwrite an existing file?

Here it is: Navigate to source file in source directory, copy (Ctrl-C), navigate to destination file in destination directory, delete destination file (Del, Enter), paste (Ctrl-V), rename (F2) and edit name to destination name.

Will Robocopy overwrite newer files?

Robocopy normally overwrites those. /XN excludes existing files newer than the copy in the source directory. Robocopy normally overwrites those. /XO excludes existing files older than the copy in the source directory.

What does file copy do?

Definition. Copies an existing file to a new file.


2 Answers

Use

File.Copy(filePath, newPath, true);

The third parameter is overwrite, so if you set it to true the destination file will be overwritten.

See: File.Copy in the MSDN

like image 146
CodesInChaos Avatar answered Oct 18 '22 19:10

CodesInChaos


There is an overload to this function that contains a third parameter. This parameter is called "overwrite". If you pass true, as long as the file is not read-only, it will be overwritten.

like image 40
davisoa Avatar answered Oct 18 '22 20:10

davisoa