简体   繁体   中英

Copy only newer files with File.Copy?

I am a bit confused about File.Copy . Initially, I was deleting a whole directory structure and then copying from a source path to a target path, but this was taking a while. Now what I am doing is only creating the directory structure on the target path if it does not already exist. If it exists, I only want to copy files if they are newer. After removing the delete, the copy goes super fast, but I am not sure if it is actually copying newer files. If I do File.Copy(source,target) , does this only copy files if the do not exist? If I do File.Copy(source,target,true) , does this copy the file regardless if it is newer or not?

File.Copy(source,target,true) will overwrite the file - regardless if it is newer or not.

Copy doesn't have logic to determine newness of files or what would be the right action.

You need to implement this logic yourself - if you only want to copy newer files, you need to compare the create dates of both files and only copy newer ones.

您应该使用FileInfo类并在逻辑中比较文件。

If I do File.Copy(source,target), does this only copy files if the do not exist?

File.Copy(source, target) will throw an IOException if the target file already exists (regardless of whether it's newer or not).

If your code "runs fast" using this, I assume that you are "swallowing exceptions" somewhere (ie have a try with an empty catch block). That's evil, because it makes your program "appear" like it is working correctly when it isn't. Don't do that! It makes debugging a nightmare.

If I do File.Copy(source,target,true), does this copy the file regardless if it is newer or not?

Yes.

If you want the files to be copied based on some attribute, you can use the File or the FileInfo class ( What's the difference? ) to get this information. You can choose between the "Creation Time", the "Last Access Time" and the "Last Write Time" (depending on how you define "newer").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM