Thursday, 4 August 2011

How to copy one folder contents into another in C#

/// <summary>
  /// Recursively copies one folder contents into another folder. Creates destination folder if it doesn't exist
  /// </summary>
  /// <param name="source"></param>
  /// <param name="target"></param>
  public static void CopyFilesTree(DirectoryInfo source, DirectoryInfo target)
  {
   if (!Directory.Exists(target.FullName)) { Directory.CreateDirectory(target.FullName); }
 
   foreach (DirectoryInfo dir in source.GetDirectories()) {
    CopyFilesTree(dir, target.CreateSubdirectory(dir.Name));
   }
 
   foreach (FileInfo file in source.GetFiles()) {
    file.CopyTo(Path.Combine(target.FullName, file.Name));
   }
  }

No comments:

Post a Comment