Moving Directory Objects

To move objects to a new container, use the MoveTo method.

The following code example shows how to use MoveTo to move a user object.

[Visual Basic .NET]

Try
    ' Bind to the object to be moved.
    Dim NewUser As New DirectoryEntry("LDAP://CN=User Name,OU=Sales,DC=fabrikam,DC=com")
    ' Use the MoveTo property to define the new container where you wish to move the object to.
    NewUser.MoveTo(New DirectoryEntry("LDAP://OU=HR,DC=fabrikam,DC=com"))
Catch Exception1 As Exception
    Select Case Exception1.GetType().ToString()
        ' If InvalidOperationException is thrown, then the DirectoryEntry is not a container.
        Case "InvalidOperationException"
        Dim InvOpEx As New InvalidOperationException()
        ' Handle error, for example Console.WriteLine(InvOpEx.Message);
        Exit 
        ' If a COMException is thrown, then the following code can catch the text of the error.
        ' For more information about handling COM exceptions, see Handling Errors.
        Case "System.Runtime.InteropServices.COMException"
        Dim COMEx As System.Runtime.InteropServices.COMException = CType(Exception1, System.Runtime.InteropServices.COMException)
        ' Handle error, for example Console.WriteLine(COMEx.ErrorCode);
        Exit 
    End Select
End Try

[C#]

try
{
    // Bind to the object to be moved.
    DirectoryEntry NewUser = new DirectoryEntry("LDAP://CN=User Name,OU=Sales,DC=fabrikam,DC=com");
    // Use the MoveTo property to define the new container where you wish to move the object to.
    NewUser.MoveTo( new DirectoryEntry("LDAP://OU=HR,DC=fabrikam,DC=com"));
}
catch (Exception Exception1)
{
    switch (Exception1.GetType().ToString())
    {
        // If InvalidOperationException is thrown, then the DirectoryEntry is not a container.
        case "InvalidOperationException":
        {
            InvalidOperationException InvOpEx = new InvalidOperationException();
            // Handle error, for example Console.WriteLine(InvOpEx.Message);
            break;
        }
        // If a COMException is thrown, then the following code can catch the text of the error.
        // For more information about handling COM exceptions, see Handling Errors.
        case "System.Runtime.InteropServices.COMException":
        {
            System.Runtime.InteropServices.COMException COMEx = 
            (System.Runtime.InteropServices.COMException) Exception1;
             // Handle error, for example Console.WriteLine(COMEx.ErrorCode);
             break;
        }
    }
}