C# Move Directory

Summary: in this tutorial, you’ll learn how to use move a directory and all of its subdirectories and files to a new directory.

Introduction to the C# Directory.Move() method

The Directory.Move() static method allows you to move a directory and its contents to a new location. Here’s the syntax of Directory.Move() static method:

public static void Move (
   string sourceDirName, 
   string destDirName
);Code language: C# (cs)

In this syntax:

  • sourceDirName is the path to a directory to move.
  • destDirName is the path to the new directory for the sourceDirName and its contents.

The Directory.Move() method carries three operations:

  • First, create a new directory with the name specified by destDirName.
  • Second, move all the files and directories from sourceDirName to the newly created destination directory.
  • Third, delete the original directory specified by the sourceDirName.

The Directory.Move() method throws an IOException in one of the following scenarios:

  • The subdirectories or files within the directory are being used by another process.
  • Both the sourceDirName and destDirname directories point to the same directory.
  • The destination directory specified by the destDirName already exists.
  • The directory specified destDirName is located on a different volume.

The Directory.Move() method also raises a DirectoryNotFoundException if the directory specified by sourceDirName is invalid.

C# Directory.Move() static method example

Suppose you have the following source directory C:\backup

c:\backup
└── 2023
   ├── 01
   |  └── readme.txt
   ├── 02
   ├── 03
   ├── 04
   ├── 05
   ├── 06
   ├── 07
   ├── 08
   ├── 09
   ├── 10
   ├── 11
   └── 12

directory: 13 file: 1Code language: plaintext (plaintext)

And you want to move the directory 2023 and all of its subdirectories and files to C:\archive directory. To do that, you can use the Directory.Move() static method as follows:

using static System.Console;

string backupDir = @"C:\backup\2023";
string archiveDir = @"C:\archive\2023";

try
{
    Directory.Move(backupDir, archiveDir);
}
catch (IOException ex)
{
    WriteLine(ex.Message);
}Code language: C# (cs)

After running the program, the C:\archive will have the directory 2023 and all of its contents under the C:\archive:

c:\archive
└── 2023
   ├── 01
   |  └── readme.txt
   ├── 02
   ├── 03
   ├── 04
   ├── 05
   ├── 06
   ├── 07
   ├── 08
   ├── 09
   ├── 10
   ├── 11
   └── 12

directory: 13 file: 1Code language: plaintext (plaintext)

And the 2023 directory in the C:\backup is deleted:

c:\backupCode language: plaintext (plaintext)

Summary

  • Use the C# Directory.Move() static method to move a directory and all of its subdirectories and files to a new location.
Was this tutorial helpful ?