Deleting LDAP Entries

Following on from my popular post on searching LDAP directories I thought I’d follow up with a simple piece of code that allows you to delete entries.

There are two ways to remove an entry. The first way is to search for a node an remove it, along with all of its children. The second way is to search for a node and remove one or more of its children. Below I will demonstrate both methods.

 

Dim dir As New LdapConnection(MySettings)

Using users As DirectoryEntry = dir.GetObject(MyQuery)
    For Each r As DirectoryEntry In users.Children
        users.Children.Remove(r)
    Next
    users.CommitChanges()
End Using

 

Above shows us searching for a node then looping through each child and removing it. We could also examine the properties and delete based on that.

If you want to delete a specific item its easier and more efficient to use the following method

 

Using users As DirectoryEntry = dir.GetObject(MyUserQuery)
    users.DeleteTree()
    users.CommitChanges()
End Using

 

In the above example we just search directly for a single node (user) then call the ‘DeleteTree’ method. It the entry we searched for had any children, they would also be deleted.

 

I hope this helps you out. Don’t forget to leave comments if this helped, or you need any more info, thanks.



Leave a Reply