'File.Copy' does not overwrite a file

C#.Net

C# Problem Overview


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);

C# Solutions


Solution 1 - C#

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: http://msdn.microsoft.com/en-us/library/9706cfs5.aspx">File.Copy in the MSDN

Solution 2 - C#

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.

Solution 3 - C#

Then call the overload

File.Copy(filePath, newPath, true);

Solution 4 - C#

From MSDN, you can do:

File.Copy(filePath, newPath, true);

Solution 5 - C#

Then use the other File.Copy(string, string, boolean). The third parameter indicates whether or not to overwrite the destination file if it exists (true if you want overwrite, false otherwise).

But what did you expect? If the function is designed to throw when the destination file exists, you need to find a way around that problem. So either:

  1. Search the documentation or Intellisense for an overload that does what you are asking.
  2. Barring that, create a wrapper around File.Copy(string, string) that deletes the destination file for you if it exists.

Solution 6 - C#

File.Copy(filePath, newPath, bool overwrite)

does it.

Solution 7 - C#

This can help you:

I use this and it works,

File.Copy(src,des,true); //(string source, string destination, bool overwrite)

Reference (MSDN): File.Copy Method (String, String, Boolean)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCaptain ComicView Question on Stackoverflow
Solution 1 - C#CodesInChaosView Answer on Stackoverflow
Solution 2 - C#davisoaView Answer on Stackoverflow
Solution 3 - C#blowdartView Answer on Stackoverflow
Solution 4 - C#CodingGorillaView Answer on Stackoverflow
Solution 5 - C#jasonView Answer on Stackoverflow
Solution 6 - C#elsniView Answer on Stackoverflow
Solution 7 - C#Shahin RahbarView Answer on Stackoverflow