How to also copy subfolder's new and modifed files?

Ken Ekholm 151 Reputation points
2021-09-21T12:33:40+00:00

This code only copies new and modified files under E:\Document but leaves all the subfolders and their new and modified files uncopied.
How do I also get the subfolder's new and modified files also copied?

  const string sourcePath = @"E:\Document";
  const string destPath = @"D:\Test";
  string[] originalFiles = Directory.GetFiles(sourcePath, "*", SearchOption.AllDirectories);

  Array.ForEach(originalFiles, (originalFileLocation) =>  {
        FileInfo originalFile = new FileInfo(originalFileLocation);
        FileInfo destFile = new FileInfo(originalFileLocation.Replace(sourcePath, destPath));
        if (destFile.Exists){
             if (originalFile.Length > destFile.Length{
                   originalFile.CopyTo(destFile.FullName, true);
             }
        }
        else {
             Directory.CreateDirectory(destFile.DirectoryName);
             originalFile.CopyTo(destFile.FullName, false);
        }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,099 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 110.8K Reputation points
    2021-09-21T13:14:16.15+00:00

    Instead of comparing the length with '>', try a different condition:

    if( originalFile.Length != destFile.Length || originalFile.LastWriteTime != destFile.LastWriteTime)
       . . .
    
    1 person found this answer helpful.
    0 comments No comments