Copy the entire contents of a directory in C#

how to copy a folder from one directory to another in c#
c# copy folder to output directory
c# copy file to directory
c# copy folder structure without files
c move directory
how to copy files and folders in c#
c# delete directory and contents
c++ copy directory

I want to copy the entire contents of a directory from one location to another in C#.

There doesn't appear to be a way to do this using System.IO classes without lots of recursion.

There is a method in VB that we can use if we add a reference to Microsoft.VisualBasic:

new Microsoft.VisualBasic.Devices.Computer().
    FileSystem.CopyDirectory( sourceFolder, outputFolder );

This seems like a rather ugly hack. Is there a better way?

Much easier

//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", 
    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));

//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", 
    File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);

Copy the entire contents of a directory in C#, Much easier //Now Create all of the directories foreach (string dirPath in Directory​.GetDirectories(SourcePath, "*", SearchOption.AllDirectories)) Directory. I want to copy the entire contents of a directory from one location to another in C#. There doesn’t appear to be a way to do this using System.IO classes without lots of recursion. There is a method in VB that we can use if we add a reference to Microsoft.VisualBasic: new Microsoft.VisualBasic.Devices.Computer().

Hmm, I think I misunderstand the question but I'm going to risk it. What's wrong with the following straightforward method?

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

EDIT Since this posting has garnered an impressive number of downvotes for such a simple answer to an equally simple question, let me add an explanation. Please read this before downvoting.

First of all, this code is not intendend as a drop-in replacement to the code in the question. It is for illustration purpose only.

Microsoft.VisualBasic.Devices.Computer.FileSystem.CopyDirectory does some additional correctness tests (e.g. whether the source and target are valid directories, whether the source is a parent of the target etc.) that are missing from this answer. That code is probably also more optimized.

That said, the code works well. It has (almost identically) been used in a mature software for years. Apart from the inherent fickleness present with all IO handlings (e.g. what happens if the user manually unplugs the USB drive while your code is writing to it?), there are no known problems.

In particular, I’d like to point out that the use of recursion here is absolutely not a problem. Neither in theory (conceptually, it’s the most elegant solution) nor in practice: this code will not overflow the stack. The stack is large enough to handle even deeply nested file hierarchies. Long before stack space becomes a problem, the folder path length limitation kicks in.

Notice that a malicious user might be able to break this assumption by using deeply-nested directories of one letter each. I haven’t tried this. But just to illustrate the point: in order to make this code overflow on a typical computer, the directories would have to be nested a few thousand times. This is simply not a realistic scenario.

C# - Copy a folder, its content and the sub-directories, There are a few different techniques to copy a directory with C#, using the command XCopy, or using a recursive method. The best one I saw was the one from  If Not Directory.Exists (destDirName) Then Directory.CreateDirectory (destDirName) End If ' Get the files in the directory and copy them to the new location. Dim files As FileInfo () = dir.GetFiles () For Each file In files Dim temppath As String = Path.Combine (destDirName, file.Name) file.CopyTo (temppath,

Copied from MSDN:

using System;
using System.IO;

class CopyDir
    public static void Copy(string sourceDirectory, string targetDirectory)
        DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
        DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

        CopyAll(diSource, diTarget);

    public static void CopyAll(DirectoryInfo source, DirectoryInfo target)

        // Copy each file into the new directory.
        foreach (FileInfo fi in source.GetFiles())
            Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
            fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);

        // Copy each subdirectory using recursion.
        foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
            DirectoryInfo nextTargetSubDir =
            CopyAll(diSourceSubDir, nextTargetSubDir);

    public static void Main()
        string sourceDirectory = @"c:\sourceDirectory";
        string targetDirectory = @"c:\targetDirectory";

        Copy(sourceDirectory, targetDirectory);

    // Output will vary based on the contents of the source directory.

C# Copy Folder Recursively : C# 411, IO that will copy a folder and its contents. Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the  C# – Copy a folder, its content and the sub-directories Hello Devz, It’s unbelievable but yes, the System.IO provided by .NET doesn’t have a simple method to copy a folder, its content and the sub directories to another destination.

Try this:

Process proc = new Process();
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "xcopy.exe");
proc.StartInfo.Arguments = @"C:\source C:\destination /E /I";

Your xcopy arguments may vary but you get the idea.

Copy the entire contents of a directory to another directory in PHP , Shallow Copy and Deep Copy in C# · How to Dim entire screen except a fixed area using JavaScript ? aman neekhara. Check out this Author's contributed articles  The following examples show how to copy, move, and delete files and folders in a synchronous manner by using the System.IO.File, System.IO.Directory, System.IO.FileInfo, and System.IO.DirectoryInfo classes from the System.IO namespace. These examples do not provide a progress bar or any other user interface.

Or, if you want to go the hard way, add a reference to your project for Microsoft.VisualBasic and then use the following:

Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(fromDirectory, toDirectory);

However, using one of the recursive functions is a better way to go since it won't have to load the VB dll.

Copy files from one directory to another directory in C#, How to copy all files and folders from one directory to another directory or location using C#. I want to move a directory as a copy/paste routine, by keeping its structure as it is. I am not looking only for the files within all subfolders in a directory then copy/paste them (as this solution), instead I want to clone the whole thing and keep its structure as it is (Tree -> subfolders and files), exactly like a copy and paste routine.

[Solved] How to copy a directory from one location to another using C#, CopyTo(temppath, false); } // If copying subdirectories, copy them and their contents to new location. if (copySubDirs) { foreach (DirectoryInfo  What is the best way to copy a folder and all subfolders and files using c#. 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..

CopyDirectory(ICakeContext, DirectoryPath , CopyDirectory(ICakeContext, DirectoryPath, DirectoryPath) Method. Summary. Copies the contents of a directory, including subdirectories to the specified location. If the directory you're copying is called dir1 and you want to copy it to your /home/Pictures folder: Linux is case-sensitive and also needs the / after each directory to know that it isn't a file. ~ is a special character in the terminal that automatically evaluates to the current user's home directory.

C# Directory tutorial - working with directories in C#, C# Directory tutorial shows how to work with directories in C#. If the copySubDirs is set, we copy subdirectories and their contents to the new  Replace C:\TestDirectory1 and C:\TestDirectory2 with the path and name of the directory you wish to copy and the location to which you wish to copy it. Remarks. This method copies the contents of the source directory to the target directory. If the target directory does not exist, it is created.

  • I would say that looking at the alternatives posted below, that the VB way doesn't look so ugly.
  • How can it be a hack when it is part of the .NET Framework? Stop writing code and use what you got.
  • That is a common misconception. Microsft.VisualBasic contains all the common Visual Basic procedures that makes coding in VB so much easier. Microsot.VisualBasic.Compatibility is the assembly used for VB6 legacy.
  • There is over 2,000 lines of code to Microsoft.VisualBasic.Devices.Computer.FileSystem. CopyDirectory ensures you are not copying a parent folder into a child folder and other checks. It is highly optimized, and so on. The selected answer is fragile code at best.
  • @AMissico - ok, so why is this optimised and complete code in Microsoft.VisualBasic and not System.IO? The reason it isn't in Mono is because all the libraries that are considered 'core' are System.[something] - all the other ones are not. I've got no problem referencing an extra DLL, but there's a good reason why Microsoft haven't included this feature in System.IO.
  • It's a nice piece of code indeed but this is not the kind of code that can be used anywhere. Developers should be careful because dirPath.Replace could cause unwanted consequences. Just a warning to people that like doing copy and paste over the net. The code posted by @jaysponsored is safer because it doesn't use string.Replace but I'm sure it also has its corner cases.
  • Be careful with this code as it will throw an exception if the target directory exists already. It will also not overwrite files that already exists. Simply add a check before creating each directory and use the overload of File.Copy to overwrite target file if exists.
  • @Xaisoft - Replace has a problem if you have a repeating pattern inside the path, for instance "sourceDir/things/sourceDir/things" should become "destinationDir/things/sourceDir/things", but if you use replace it becomes "destinationDir/things/destinationDir/things"
  • Why *.* instead of *? Don't you want to copy files without extensions too?
  • Let's build something and contribute it to the Open Source .NET Core... :/
  • This is head recursion. It can fall prey to a stack overflow if the directories are nested deep enough.
  • Until very recently, directory nesting depth was restricted by the OS. I doubt that you'll find directories that are nested more than a few hundred times (if even). The above code can take much more.