This post will discuss how to move a directory to another location in C#.

1. Using Directory.Move() method

You can move the entire directory using the Directory class from the System.IO namespace. The Directory.Move() method is often used to move a directory and its contents to the specified location. The following example shows the usage of the Directory.Move() method by moving the directory specified by srcDir to the directory specified by destDir.

Download Code

 
Note that either the source or destination directory can be relative or absolute. The Directory.Move() method throws IOException if the destination directory already exists, and DirectoryNotFoundException if the source or the destination path cannot be found. You can handle them as shown below:

Download Code

 
You may want to delete the destination folder if it already exists. The following example copies a directory’s contents to a new location, which can be an existing directory:

Download Code

2. Using DirectoryInfo.MoveTo() method

Another option is to use the DirectoryInfo.MoveTo() method for moving a DirectoryInfo instance and its contents to a new path. The following example demonstrates moving a directory using the DirectoryInfo class.

Download Code

 
To avoid getting any exceptions, you can ensure that the source path specified by srcDir exist and the destination path specified by destDir does not exist. If the destination directory exists, delete all files and subdirectories in it before moving.

Download Code

That’s all about moving a directory to another location in C#.