Updated on

To copy a directory and all of its contents in C#, we first recreate its folder tree under the destination and then copy every file into it. System.IO has no method that does both, so we write a short helper ourselves.

Then we’ll turn the helper into an extension method and look at the one ready-made method .NET does ship for the job.

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

How to Copy a Directory and All Its Contents to Another Directory?

First, let’s review how we want to approach the problem before we code. Since we are trying to do a deep copy of a directory, we want to make sure all directories exist before we copy files. Then we are free to copy all files from the source path to the destination path.

Both steps need the same small calculation. For each folder and file under the source, we take its path relative to the source with Path.GetRelativePath() and join it onto the destination with Path.Join(). Copying from data to backup turns data\database\notes.txt into backup\database\notes.txt.

Directory.GetDirectories() and Directory.GetFiles() with SearchOption.AllDirectories return every folder and file at any depth, so we don’t need recursion.

Existing folders at the destination cause no trouble. Existing files do: File.Copy() throws an IOException when the target file is already there, unless we pass true for its overwrite parameter.

We start by creating a directory at the destinationDir path for each directory and sub-directory under the sourceDir path. Note that GetDirectories() returns the sub-directories at every level because we specified SearchOption.AllDirectories and a wildcard search pattern *.

Now, let’s take a look at how we can implement this. The two code blocks in this section, in order, form the body of a public static void CopyDirectory(string sourceDir, string destinationDir, bool overwriteFiles) method, which we keep in a static class in its own file:

var allDirectories = Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories);

foreach (string dir in allDirectories)
{
    string dirToCreate = Path.Join(destinationDir, Path.GetRelativePath(sourceDir, dir));
    Directory.CreateDirectory(dirToCreate);
}

Directory.CreateDirectory(destinationDir);

We create destinationDir itself after the loop because the loop only creates sub-directories. Without that line, a source with files but no sub-folders throws a DirectoryNotFoundException as soon as we copy the first file into a destination that does not exist yet.

Why not dir.Replace(sourceDir, destinationDir)? Because string.Replace() swaps every match in the path, wherever it sits. With a relative source path data, the folder data\database came out as backup\backupbase when we ran it. On Linux, absolute paths run into the same thing: "/data/database".Replace("/data", "/backup") returns /backup/backupbase. Path.GetRelativePath() works on whole path segments, so the folder names survive. Our article on the Path class covers Path.Join() and the rest of its methods.

Because Path uses the separator of the system it runs on, the same code works on Windows, Linux and macOS.

Now that all directories are created, we can copy all files in all directories. Similarly, GetFiles() returns all files in all directories because we specified SearchOption.AllDirectories and a file wild card search pattern *.*:

var allFiles = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories);

foreach (string newPath in allFiles)
{
    string newFile = Path.Join(destinationDir, Path.GetRelativePath(sourceDir, newPath));
    File.Copy(newPath, newFile, overwriteFiles);
}

Existing directories at the target location are fine, and what happens to existing files depends on overwriteFiles. With true, File.Copy() replaces them, and with false, it throws an IOException at the first file that is already there. Files that exist only in the destination stay where they are: the copy merges into the destination folder and never deletes anything there.

The *.* pattern also matches files with no extension, such as a README.

Lastly, let’s explore the SearchOption enum. In this solution, we are using AllDirectories since we want to copy all content under the sourceDir. The other option is SearchOption.TopDirectoryOnly which indicates operations should only occur under sourceDir and no other child directory. We use the same option when we count the files in a folder and its sub-folders.

Copy a Directory as DirectoryInfo Class Extension Method

In this section, we will add DeepCopy() as an extension method of the DirectoryInfo class. This is a great way to integrate the deep copy operation into a .NET class we already use to deal with directories.

Let’s start by creating a class with an extension method DeepCopy():

public static class DirectoryInfoExtensions
{
    public static void DeepCopy(this DirectoryInfo directory, string destinationDir, bool overwriteFiles)
    {
        foreach (string dir in Directory.GetDirectories(directory.FullName, "*", SearchOption.AllDirectories))
        {
            string dirToCreate = Path.Join(destinationDir, Path.GetRelativePath(directory.FullName, dir));
            Directory.CreateDirectory(dirToCreate);
        }

        Directory.CreateDirectory(destinationDir);

        foreach (string newPath in Directory.GetFiles(directory.FullName, "*.*", SearchOption.AllDirectories))
        {
            string newFile = Path.Join(destinationDir, Path.GetRelativePath(directory.FullName, newPath));
            File.Copy(newPath, newFile, overwriteFiles);
        }
    }
}

Now we can import the namespace that contains our code and use the method:

var sourceDir = new DirectoryInfo(sourcePath);
sourceDir.DeepCopy(destinationPath, true);

The second argument is overwriteFiles, the same flag as in our first version. Note that in this example of the solution we do not need the source directory path as a string in DeepCopy(). We can access this same value by referencing the DirectoryInfo.FullName property.

A Few Edge Cases to Consider

Let’s take a look at some common exceptions we may run into running this code.

First, we may see UnauthorizedAccessException. This may occur during any file system operation on entries that have permission restrictions. Make sure the current user has permissions to the sourceDir and destinationDir to avoid permission exceptions.

Next, let’s consider IOException. IOException may occur when the path passed to a function is a file when a directory path was expected. We cover how to tell whether a path is a file or a directory in a separate article.

Lastly, DirectoryNotFoundException may occur when the path passed to a function does not exist or is an invalid path. Checking paths with Directory.Exists() or File.Exists() can avoid getting these exceptions.

What if the destination sits inside the source folder, say src\backup? The first copy works. On the next run, the earlier copy is part of the source, so it gets copied again one level deeper. Our second run produced src\backup\backup\sub\a.txt. We should keep the destination outside the source, or leave it out of both lists.

Links are followed. When the source contained a junction to another folder, our copy on Windows wrote the files behind it into the destination as ordinary files and created no link.

Of course, these are not the only exceptions that can happen and you need to check your own code for other possible edge cases.

Is There a Built-In Method to Copy a Directory in C#?

Not in System.IO. Neither Directory nor DirectoryInfo has a copy method on .NET 11, and Microsoft Learn’s own “How to: Copy directories” page answers the question with a recursive helper method.

There is one ready-made option in another namespace. Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory() copies a folder with all of its sub-folders and files in a single call. It lives in the Microsoft.VisualBasic.Core assembly, which ships with .NET, so a C# project can call it without a NuGet package.

It doesn’t behave exactly like our helper, though. It creates a missing destination folder and merges into an existing one. With overwrite left at false, it copies every file it can, then throws one IOException whose Data property lists the files it skipped. It also refuses to copy a folder into one of its own sub-folders and throws an InvalidOperationException instead.

Microsoft Learn’s reference for the method puts the merge rule in one sentence: “If a directory with the same name exists in the target location, the contents of the two directories are merged.”

Calling it from C# takes one using directive and one line:

using Microsoft.VisualBasic.FileIO;

FileSystem.CopyDirectory(sourcePath, destinationPath, overwrite: true);

We keep this call out of the file that holds our helper. Microsoft.VisualBasic.FileIO has a SearchOption enum of its own, so with this using in that file, SearchOption becomes ambiguous and the build fails with CS0104.

So which one should we use? If merging and a single error list suit the job, CopyDirectory() saves us the helper. When we want control over each file, for example to skip some of them, or to test the copy against a fake file system as the tests in our sample do, the hand-written version is the better fit.

Conclusion

In this short article, we’ve learned how to copy a directory’s contents to another directory, and what to watch for: existing files, a destination inside the source, and links. We can take this solution and apply it in many different contexts to improve our file management. Additionally, we can integrate it easily, using extension methods, into a currently existing class in our codebase that’s already doing some file management operations.

When one call is enough and merging suits us, FileSystem.CopyDirectory() does the job out of the box.

Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and MSTest 4.5.3.