'File.Copy' does not overwrite a file

后端 未结 7 1091
暗喜
暗喜 2020-11-30 11:08

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, newPa         


        
相关标签:
7条回答
  • 2020-11-30 11:13

    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

    0 讨论(0)
  • 2020-11-30 11:14

    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.

    0 讨论(0)
  • 2020-11-30 11:17

    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)

    0 讨论(0)
  • 2020-11-30 11:24

    Then call the overload

    File.Copy(filePath, newPath, true);
    
    0 讨论(0)
  • 2020-11-30 11:30

    From MSDN, you can do:

    File.Copy(filePath, newPath, true);
    
    0 讨论(0)
  • 2020-11-30 11:38

    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.
    0 讨论(0)
提交回复
热议问题