DirectoryInfo.MoveTo(String) Method

Definition

Moves a DirectoryInfo instance and its contents to a new path.

C#
public void MoveTo(string destDirName);

Parameters

destDirName
String

The name and path to which to move this directory. The destination cannot be another disk volume or a directory with the identical name. It can be an existing directory to which you want to add this directory as a subdirectory.

Exceptions

destDirName is null.

destDirName is an empty string (''").

An attempt was made to move a directory to a different volume.

-or-

destDirName already exists.

-or-

You are not authorized to access this path.

-or-

The directory being moved and the destination directory have the same name.

The caller does not have the required permission.

The destination directory cannot be found.

Examples

The following example demonstrates moving a directory.

C#
using System;
using System.IO;

public class MoveToTest
{
    public static void Main()
    {

        // Make a reference to a directory.
        DirectoryInfo di = new DirectoryInfo("TempDir");

        // Create the directory only if it does not already exist.
        if (!di.Exists)
            di.Create();

        // Create a subdirectory in the directory just created.
        DirectoryInfo dis = di.CreateSubdirectory("SubDir");

        // Move the main directory. Note that the contents move with the directory.
        if (!Directory.Exists("NewTempDir"))
            di.MoveTo("NewTempDir");

        try
        {
            // Attempt to delete the subdirectory. Note that because it has been
            // moved, an exception is thrown.
            dis.Delete(true);
        }
        catch (Exception)
        {
            // Handle this exception in some way, such as with the following code:
            // Console.WriteLine("That directory does not exist.");
        }

        // Point the DirectoryInfo reference to the new directory.
        //di = new DirectoryInfo("NewTempDir");

        // Delete the directory.
        //di.Delete(true);
    }
}

Remarks

This method throws an IOException if, for example, you try to move c:\mydir to c:\public, and c:\public already exists. You must specify "c:\public\mydir" as the destDirName parameter, or specify a new directory name such as "c:\newdir".

This method permits moving a directory to a read-only directory. The read/write attribute of neither directory is affected.

For a list of common I/O tasks, see Common I/O Tasks.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

See also