Recursively Copy folder contents to another in C#

The code snippet given below have a method CopyFolderContents() which will take two parameters "SourcePath" and "DestinationPath" and it will copy all the content in the directory "SourcePath" to "DestinationPath" recursively

Code Snippet
  1. private bool CopyFolderContents(string SourcePath, string DestinationPath)
  2. {
  3.    SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
  4.    DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
  5.    try
  6.    {
  7.       if (Directory.Exists(SourcePath))
  8.       {
  9.          if (Directory.Exists(DestinationPath) == false)
  10.          {
  11.             Directory.CreateDirectory(DestinationPath);
  12.          }
  13.          foreach (string files in Directory.GetFiles(SourcePath))
  14.          {
  15.             FileInfo fileInfo = new FileInfo(files);
  16.             fileInfo.CopyTo(string.Format(@"{0}\{1}", DestinationPath, fileInfo.Name), true);
  17.          }
  18.          foreach (string drs in Directory.GetDirectories(SourcePath))
  19.          {
  20.             DirectoryInfo directoryInfo = new DirectoryInfo(drs);
  21.             if (CopyFolderContents(drs, DestinationPath + directoryInfo.Name) == false)
  22.             {
  23.                return false;
  24.             }
  25.          }
  26.       }
  27.       return true;
  28.    }
  29.    catch (Exception ex)
  30.    {
  31.       return false;
  32.    }
  33. }


Post a Comment