DirectoryInfo.MoveTo(String) Метод

Определение

Перемещает экземпляр DirectoryInfo и его содержимое в местоположение, на которое указывает новый путь.

public:
 void MoveTo(System::String ^ destDirName);
public void MoveTo (string destDirName);
member this.MoveTo : string -> unit
Public Sub MoveTo (destDirName As String)

Параметры

destDirName
String

Имя и путь к местоположению, в которое необходимо переместить указанный каталог. Место назначения не должно находиться на другом томе устройства или в каталоге с идентичным именем. Оно должно представлять собой существующий каталог, в который перемещаемый каталог будет добавлен в виде подкаталога.

Исключения

destDirName имеет значение null.

destDirName является пустой строкой ("").

Была предпринята попытка переместить каталог в другой том.

-или-

destDirName уже существует.

-или-

Отсутствует авторизация для доступа по этому пути.

-или-

Каталог перемещается, и каталог назначения имеет то же самое имя.

У вызывающего объекта отсутствует необходимое разрешение.

Не удалось найти каталог назначения.

Примеры

В следующем примере показано перемещение каталога.

using namespace System;
using namespace System::IO;
int main()
{
   
   // Make a reference to a directory.
   DirectoryInfo^ di = gcnew 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(S"That directory does not exist.");
   }

   
   // Point the DirectoryInfo reference to the new directory.
   //di = new DirectoryInfo(S"NewTempDir");
   // Delete the directory.
   //di->Delete(true);
}
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 == false)
            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") == false)
            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);
    }
}
open System.IO

// Make a reference to a directory.
let di = DirectoryInfo "TempDir"

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

// Create a subdirectory in the directory just created.
let dis = di.CreateSubdirectory "SubDir"

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

try
    // Attempt to delete the subdirectory. Note that because it has been
    // moved, an exception is thrown.
    dis.Delete true
with _ ->
    // 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)
Imports System.IO

Public Class MoveToTest

    Public Shared Sub Main()
        ' Make a reference to a directory.
        Dim di As New DirectoryInfo("TempDir")
        ' Create the directory only if it does not already exist.
        If di.Exists = False Then
            di.Create()
        End If

        ' Create a subdirectory in the directory just created.
        Dim dis As DirectoryInfo = di.CreateSubdirectory("SubDir")
        If Directory.Exists("NewTempDir") = False Then
            ' Move the main directory. Note that the contents move with the directory.
            di.MoveTo("NewTempDir")
        End If
        Try
            ' Attempt to delete the subdirectory. Note that because it has been
            ' moved, an exception is thrown.
            dis.Delete(True)
        Catch
            ' 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)        
        End Try

    End Sub
End Class

Комментарии

Этот метод вызывает исключение IOException , если, например, вы пытаетесь переместить c:\mydir в папку c:\public, а c:\public уже существует. В качестве destDirName параметра необходимо указать "c:\\public\\mydir" или указать новое имя каталога, например "c:\\newdir".

Этот метод позволяет перемещать каталог в каталог, доступный только для чтения. Атрибут чтения и записи в каталоге не затрагивается.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

Применяется к

См. также раздел