65.9K
CodeProject is changing. Read more.
Home

Recursively Copy folder contents to another in C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.43/5 (5 votes)

Nov 6, 2011

CPOL
viewsIcon

52732

How to recursively copy folder contents to another in C#.

private bool CopyFolderContents(string SourcePath, string DestinationPath)
{
   SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
   DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
 
   try
   {
      if (Directory.Exists(SourcePath))
      {
         if (Directory.Exists(DestinationPath) == false)
         {
            Directory.CreateDirectory(DestinationPath);
         }

         foreach (string files in Directory.GetFiles(SourcePath))
         {
            FileInfo fileInfo = new FileInfo(files);
            fileInfo.CopyTo(string.Format(@"{0}\{1}", DestinationPath, fileInfo.Name), true);
         }

         foreach (string drs in Directory.GetDirectories(SourcePath))
         {
            DirectoryInfo directoryInfo = new DirectoryInfo(drs);
            if (CopyFolderContents(drs, DestinationPath + directoryInfo.Name) == false)
            {
               return false;
            }
         }
      }
      return true;
   }
   catch (Exception ex)
   {
      return false;
   }
}