I have a VB application (.NET 4.0) where a user selects an AD group they own, then can add users from a predefined list to that group. The groups and pulled from AD and the users are pulled from Oracle but are all existing AD users.
You will see three commented code blocks, I have tried all three and get "COMException was unhandled by user code: Unspecified error" with each one.
<WebMethod()> _
Public Shared Function AddDirectReport(ByVal User As String, ByVal Group As String) As String
Dim GroupMembers As List(Of String) = LoadGroupMembers(Group)
If GroupMembers.Contains(User) Then
Return "USER " & User & " IS ALREADY IN GROUP " & Group
End If
Dim SearchRoot As New DirectoryEntry("[LDAP Path]")
Dim GroupSearcher As New DirectorySearcher
With GroupSearcher
.SearchRoot = SearchRoot
.Filter = "(&(ObjectClass=Group)(CN=" & Group & "))"
End With
Dim UserSearcher As New DirectorySearcher
With UserSearcher
.SearchRoot = SearchRoot
.Filter = "(&(ObjectClass=Person)(CN=" & User & "))"
End With
Dim g As DirectoryEntry = GroupSearcher.FindOne.GetDirectoryEntry
Dim u As DirectoryEntry = UserSearcher.FindOne.GetDirectoryEntry
'With u
' .Properties("memberof").Add(g)
' .CommitChanges()
'End With
'With g
' .Properties("member").Add(u)
' .CommitChanges()
'End With
'With g
' .Properties("members").Add(u)
' .CommitChanges()
'End With
Return "Success?"
End Function
This is a great resource.
In it, you'll find that your second was almost there. Instead of passing the DirectoryEntry to the add method, you need its distinguished name:
With g
.Properties("member").Add(u.Properties("distinguishedName").Value)
.CommitChanges()
End With