Aubrey Love

Aubrey Love

  • NA
  • 173
  • 4.9k

Copy only new or modified files/directories in C#

Mar 13 2019 10:51 AM

I know this has probably been done and discussed umpteen times, but I can’t find the answer I am looking for.

I am trying to create a simple “directory/file copy" console application in C#.

What I need is to copy all folders and files (keeping the original hierarchy) from one drive to another, like from drive C:\Data to drive E:\Data.

However, I only want it copy any new or modified folders and files. If the folder or file on the destination drive is newer than the one on the source drive, then it does not copy.

Here is the code I have tried, but it’s not working. Any suggestions? Thank you. 

  1. class Copy  
  2. {  
  3.     public static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)  
  4.     {  
  5.         if (!destination.Exists)  
  6.         {  
  7.             destination.Create();  
  8.         }  
  9.         // Copy files.  
  10.         FileInfo[] files = source.GetFiles();  
  11.         FileInfo[] destFiles = destination.GetFiles();  
  12.         foreach (FileInfo file in files)  
  13.             foreach (FileInfo fileD in destFiles)  
  14.                 // Copy only modified files  
  15.                 if (file.Exists)  
  16.                 {  
  17.                     if (file.LastWriteTime > fileD.LastWriteTime)  
  18.                     {  
  19.                         file.CopyTo(Path.Combine(destination.FullName,  
  20.                         file.Name), true);  
  21.                     }  
  22.                 }  
  23.                 // Copy all new files  
  24.                 else  
  25.                 if (!fileD.Exists)  
  26.                 {  
  27.                     file.CopyTo(Path.Combine(destination.FullName, file.Name), true);  
  28.                 }  
  29.         // Process subdirectories.  
  30.         DirectoryInfo[] dirs = source.GetDirectories();  
  31.         foreach (DirectoryInfo dir in dirs)  
  32.         {  
  33.             // Get destination directory.  
  34.             string destinationDir = Path.Combine(destination.FullName, dir.Name);  
  35.             // Call CopyDirectory() recursively.  
  36.             CopyDirectory(dir, new DirectoryInfo(destinationDir));  
  37.         }  
  38.     }  
  39. }  
 

Answers (5)