Add a user to an Active Directory group with VB.Net

Posted: 12-12-2006

I've been needing a way to add users to an Active Directory group and I was wanting to use either C# or VB.NET from the Framework 2 or 3 to accomplish this (as opposed to VBScript). I had a hard time finding examples anywhere that accomplished my task so I decided to dig in until I got something to work... below is a Sub that successfully added an Active Directory user into a specified group via LDAP. The tricky part for most will likely be finding the LDAP address (I used a copy of Hyena to quickly find it).

The below is a simple Sub to accomplish this, It's bare bones, but does the trick. I haven't taken the time to make it into it's own class yet though I intend to make an Active Directory Object class for the average Joe coder since a lot of the ones I've seen are themselves very cumbersome to use.

Be sure before you start to add a reference in your project to System.DirectoryServices. This is the namespace where all the magic comes from. My apologies for the word wrapping, the blog display area is fairly small, it should copy and paste fine though.

    ' Put this import at the top of your class, you will need to add a reference to your project to System.DirectoryServices
    Imports System.DirectoryServices
    Private Sub adUserToGroup()
        ' sDomainName represents the location of your LDAP server
        Dim sDomainName As String = "LDAP://"
        Dim adUserFolder As DirectoryEntry = New DirectoryEntry("LDAP://,DC=yourdomain,DC=edu")

        ' This user is an active directory user and it will need access to write to the group you're trying to add to
        adUserFolder.Username = "insert user to authenticate as"
        adUserFolder.Password ="insert password"
        Dim adSearch As New System.DirectoryServices.DirectorySearcher(adUserFolder)

        ' group1 represents the active directory group name
        adSearch.Filter = String.Format("(&(objectCategory=group)(sAMAccountName= {0}))", "group1")

        ' There should only be one entry in this group because you listed the exact address, if it returned multiple
        ' you would be adding this user to all of those groups which could easily manifest into an issue if not used
        ' properly. I see this as a very controled script though so it shouldn't be an issue.
        For Each x As SearchResult In adSearch.FindAll
            Dim group As DirectoryEntry = x.GetDirectoryEntry
            ' bpell being the name of the user that you want to add.
            ' If you wanted to see the members of the group instead of adding, comment out the lines that add the entry and
            ' uncomment the below loop which will iterate through the AD group members
            'For Each s As String In x.GetDirectoryEntry().Properties("member")
            '    Msgbox(s)
    End Sub