简体   繁体   中英

Copy only files that are newer

I am currently using this code:

    if (!Directory.Exists(command2)) Directory.CreateDirectory(command2);

    if (Directory.Exists(vmdaydir)) Directory.Delete(vmdaydir,true);

    if (!Directory.Exists(vmdaydir)) Directory.CreateDirectory(vmdaydir);

    var dir = Path.GetDirectoryName(args[0]);

    sb.AppendLine("Backing Up VM: " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
    Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(dir, vmdaydir);
    sb.AppendLine("VM Backed Up: " + DateTime.Now.ToString(CultureInfo.InvariantCulture));

As you can see, I am deleting the directory, then I am copying the folder back. This is taking way to long since the directory is ~80gb in size. I realized that I do not need to copy all the files, only the ones that have changed.

How would I copy the files from one folder to another but only copying the files that are newer? Anyone have any suggestions?

==== edit ====

I assume I can just do a file compare of each file and then copy it to the new directory, iterating through each folder/file? Is there a simpler way to do this?

Use the FileInfo class, and use the LastWriteTime property to get the last modified time of the file. Compare it to the time you're checking against and take only files that are later.

Loop through the files in the directory, checking the last modified time (FileInfo.LastWriteTime) - any files that are newer are copied over.

See FileInfo Class for more information.

You need to be careful when trying to do this that you can get a lock on the file otherwise another application may not be finished with it and you may try to copy it before you are ready.

So follow these steps...

1) attempt to lock file

2) if(got lock) copy file

3) else wait a short time

4) goto 1

:)

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