This post will discuss how to move all files from one folder to another in C#.

1. Using Directory.Move() method

The standard solution to move a directory and all its contents to a new location is the Directory.Move() method. It accepts the path of the directory to move, and the destination path. It works by creating a new destination directory and moving all contents of the source folder to it. The move includes all files and subdirectories present in the source directory. Finally, it deletes the source directory. Note, both source and destination can be relative or absolute paths.

Download Code

 
If you attempt to move to a directory that already exists, the system will throw an IOException exception. If the specified source path is invalid, the DirectoryNotFoundException exception is thrown. Before invoking the Directory.Move() method, you might want to explicitly check if the source folder exists and the destination doesn’t.

Download Code

 
If you want to overwrite the destination directory if it already exists, you can do so by invoking the Directory.Delete() method. The following example illustrates.

Download Code

2. Using FileInfo.MoveTo() method

If you need to move only the files present in the source location to the destination, you can do so using the MoveTo() method from the FileInfo class. It takes the destination path and moves the specified file to it. To move all files in a directory, you need to individually invoke the MoveTo() method for each file.

Download Code

 
The system throws DirectoryNotFoundException if the source or the destination directory does not exist. Additionally, FileInfo.MoveTo() cannot overwrite an existing file in the destination directory, and IOException is raised. The following program handles both:

Download Code

3. Using File.Move() method

Alternatively, you can use the File.Move() method to move all files present in the source directory to the destination directory. Similar to the MoveTo() method, you need to invoke the Move() method for each file.

The following code example demonstrates calling this method. Note, it uses the EnumerateFiles() method over the GetFiles() method, which returns an enumerable collection of file names instead of loading all the file names in memory.

Download Code

 
The above program throws DirectoryNotFoundException if either of the directories doesn’t exist. Additionally, if a file already exists in the destination directory, the IOException exception is thrown. Both these cases can be handled as follows:

Download Code

That’s all about moving all files from one folder to another in C#.