Tutorial :What is the best way to copy a folder and all subfolders and files using c#



Question:

I need to copy a Folder from one drive to a removable Hard disk. The Folder which needs to be copied will have many sub folders and files in it. The input will be Source Path and Target Path.

Like..

Source Path : "C:\SourceFolder"

Target Path : "E:\"

After copying is done, i shud be able to see the folder "SourceFolder" in my E: drive.

Thanks.


Solution:1

I think this is it.

public static void CopyFolder(DirectoryInfo source, DirectoryInfo target) {      foreach (DirectoryInfo dir in source.GetDirectories())          CopyFolder(dir, target.CreateSubdirectory(dir.Name));      foreach (FileInfo file in source.GetFiles())          file.CopyTo(Path.Combine(target.FullName, file.Name));  }  


Solution:2

Found this at Channel9. Haven't tried it myself.

public static class DirectoryInfoExtensions  {      // Copies all files from one directory to another.      public static void CopyTo(this DirectoryInfo source,               string destDirectory, bool recursive)      {          if (source == null)              throw new ArgumentNullException("source");          if (destDirectory == null)              throw new ArgumentNullException("destDirectory");          // If the source doesn't exist, we have to throw an exception.          if (!source.Exists)              throw new DirectoryNotFoundException(                      "Source directory not found: " + source.FullName);          // Compile the target.          DirectoryInfo target = new DirectoryInfo(destDirectory);          // If the target doesn't exist, we create it.          if (!target.Exists)              target.Create();          // Get all files and copy them over.          foreach (FileInfo file in source.GetFiles())          {              file.CopyTo(Path.Combine(target.FullName, file.Name), true);          }          // Return if no recursive call is required.          if (!recursive)              return;          // Do the same for all sub directories.          foreach (DirectoryInfo directory in source.GetDirectories())          {              CopyTo(directory,                   Path.Combine(target.FullName, directory.Name), recursive);          }      }  }  

and the usage looks like this:

var source = new DirectoryInfo(@"C:\users\chris\desktop");  source.CopyTo(@"C:\users\chris\desktop_backup", true);  


Solution:3

How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/cc148994.aspx

How to: Iterate Through a Directory Tree (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/bb513869.aspx


Solution:4

 private static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)          {              bool ret = true;              try              {                  SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";                  DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";                    if (Directory.Exists(SourcePath))                  {                      if (Directory.Exists(DestinationPath) == false)                          Directory.CreateDirectory(DestinationPath);                        foreach (string fls in Directory.GetFiles(SourcePath))                      {                          FileInfo flinfo = new FileInfo(fls);                          flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);                      }                      foreach (string drs in Directory.GetDirectories(SourcePath))                      {                          DirectoryInfo drinfo = new DirectoryInfo(drs);                          if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)                              ret = false;                      }                      Directory.CreateDirectory(DI_Target + "//Database");                  }                  else                  {                      ret = false;                  }              }              catch (Exception ex)              {                  ret = false;              }              return ret;          }  


Solution:5

for googlers: in pure win32/C++, use SHCreateDirectoryEx

inline void EnsureDirExists(const std::wstring& fullDirPath)  {      HWND hwnd = NULL;      const SECURITY_ATTRIBUTES *psa = NULL;      int retval = SHCreateDirectoryEx(hwnd, fullDirPath.c_str(), psa);      if (retval == ERROR_SUCCESS || retval == ERROR_FILE_EXISTS || retval == ERROR_ALREADY_EXISTS)          return; //success        throw boost::str(boost::wformat(L"Error accessing directory path: %1%; win32 error code: %2%")           % fullDirPath          % boost::lexical_cast<std::wstring>(retval));        //TODO *djg* must do error handling here, this can fail for permissions and that sort of thing  }  


Solution:6

Why dont you use something like Robocopy?

It has a mirroring option where the directory structure of source is copied as-is inot te destination. There are various command line options. Might save you the effort to replicate the features in your code.


Solution:7

And here is a different take on the problem:

System.Diagnostics.ProcessStartInfo psi =    new System.Diagnostics.ProcessStartInfo(@"XCOPY C:\folder D:\Backup\folder /i");  psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;  psi.UseShellExecute = false;  System.Diagnostics.Process copyFolders = System.Diagnostics.Process.Start(psi);  copyFolders.WaitForExit();  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »