开发者

File copy if target doesn't exist or source is newer

I only need to copy a file from a remote server to a local PC if:

  1. No target file on local PC yet.
  2. Source file on server is newer than target on local PC.

Source file is 4 MB so I want to avoid copying every time.

// File copy if target doesn't exist or source is newer:
if (File.Exists(filenameSource))
{
  if (File.Exists(filenameTarget))
  {
    DateTime dateSource = File.GetLastWriteTimeUtc(filenameSource);
    DateTime dateTarget = File.GetLastWriteTimeUtc(filenameTarget);

    if (dateTarget < dateSource)
    {
      File.Copy(filenameSource, filenameTarget, true);
    }
  }
  else
  {
    File.Copy(filenameSource, filenameTarget);
  }
}

My questions are:

  1. Does the above code still have to stream 4 MB of data in order to obtain the source's modified timestamp?

  2. Is comparing the modified timestamps sufficient for what I am trying to do? Or should I also compare c开发者_如何学Goreated timestamps?

(#2 Might seem like a dumb question, but what if I drop a new source file with a modified timestamp that is older than the target's modified timestamp?)

Bonus:

What if I write the above code in VBScript? Does the code below have to stream 4 MB of data in order to create the fileSource object?

if filesys.FileExists(strSource) then
  if filesys.FileExists(strTarget) then
    set fileSource = filesys.GetFile(strSource)
    set fileTarget = filesys.GetFile(strTarget)
    dateSource = fileSource.DateLastModified 
    dateTarget = fileTarget.DateLastModified 
    if dateTarget < dateSource then
      filesys.CopyFile strSource, strTarget, true
    end if
  else
    filesys.CopyFile strSource, strTarget, false
  end if
end if 


  1. Accessing size and timestamps does not require the entire file to be yanked over the network.

  2. I would include created, modified and size. To be perfectly safe, you'd have to calculate a hash, but that does require accessing the 4MB. Only you can determine whether this is an acceptable risk.

And VBScript should be the same thing.


If you're just using a UNC file share or something similar, no it won't download the entire file to check just the Date. Regarding #2: the last modified should be sufficient since the last modified should never be older than the created date.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜