简体   繁体   English

使用File.Copy仅复制较新的文件?

[英]Copy only newer files with File.Copy?

I am a bit confused about File.Copy . 我对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? 如果我执行File.Copy(source,target) ,这只会复制不存在的文件吗? 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) ,这是否复制文件,无论它是否较新?

File.Copy(source,target,true) will overwrite the file - regardless if it is newer or not. File.Copy(source,target,true)将覆盖文件-不管它是否是新的。

Copy doesn't have logic to determine newness of files or what would be the right action. Copy没有逻辑来确定文件的新颖性或正确的操作。

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),这是否仅复制不存在的文件?

File.Copy(source, target) will throw an IOException if the target file already exists (regardless of whether it's newer or not). 如果目标文件已经存在(无论是否更新),File.Copy(source,target)都将引发IOException

If your code "runs fast" using this, I assume that you are "swallowing exceptions" somewhere (ie have a try with an empty catch block). 如果使用此代码“快速运行”,则假定您正在某个地方“吞下异常”(即try使用空的catch块)。 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? 如果我执行File.Copy(source,target,true),这是否复制文件,而不管它是否较新?

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. 如果要基于某些属性复制文件,则可以使用FileFileInfo类 (有什么区别?来获取此信息。 You can choose between the "Creation Time", the "Last Access Time" and the "Last Write Time" (depending on how you define "newer"). 您可以在“创建时间”,“上次访问时间”和“上次写入时间”之间进行选择(取决于定义“较新”的方式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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