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);
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.
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.
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.
Definition. Copies an existing file to a new file.
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
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.
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