locked
unable to get groups name from user name in Active Directory RRS feed

  • Question

  • User-846088618 posted

    good day to all, I am looking for to find group name for the current user but unable to find it using following code. it returns me the 1st group in the list .however it is returning all groups using for each loop with the below function. what i m missing . please help

     Private Function GetGroupName() as string

    Dim dEntry As DirectoryEntry = New DirectoryEntry(sADPath, sUserName, sPassword)

    Dim sResult As SearchResult

    Try

    'Pass directory entry object for searchingDim dSearch As New DirectorySearcher(dEntry)

    dSearch.SearchRoot = dEntry

    dSearch.Filter = ("(objectClass= group)")

    dSearch.PropertiesToLoad.Add("member")

    sResult = dSearch.FindOne()

    Catch ex As Exception

    Throw New Exception("Error finding group" & ex.Message)

    End Try

    GetGroupNames = sResult.GetDirectoryEntry().Name.ToString()

    Friday, November 14, 2008 3:58 PM

Answers

  • User-846088618 posted

    Hey guys,

    I found the solution and sharing  with others. Have Fun

     Private Function GetUserGroup() As StringCollection

    ' wrote the following to enumerate the groups the user is a member of:

    ' you must have an active directory object of the root directory established

    ' first, then the following code should work

    ' set up a collection to hold the groups

    Dim groups As New StringCollection()

    Dim dEntry As DirectoryEntry = New DirectoryEntry(LDAP://ServerName)

    Dim srch As New DirectorySearcher(dEntry, "(sAMAccountName=" & UserName & ")")

    ' set properties to retrieve

    srch.PropertiesToLoad.Add("memberOf")

    srch.PropertiesToLoad.Add("sAMAccountName")

    ' find one entry since there should be no duplicates of sam account name

    ' in the active directory

    Dim res As SearchResult = srch.FindOne()

    ' clear the groups collection for safe measure

    groups.Clear()

    ' get the number of groups that the user is a member of

    Dim propertyCount As Integer = res.Properties("memberOf").Count

    ' create some variables for the looping through groups

    Dim dn As String

    Dim equalsIndex As Integer, commaIndex As Integer

    ' loop through groups

    For propertyCounter As Integer = 0 To propertyCount - 1

    dn = DirectCast(res.Properties("memberOf")(propertyCounter), String)

    ' the following is used to remove the cn= etc...

    equalsIndex = dn.IndexOf("=", 1)

    commaIndex = dn.IndexOf(",", 1)

    If -1 = equalsIndex Then

    Else

    ' add string to group collection

    groups.Add(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1))

    End If

    Next

    GetUserGroup = groups

    End Function

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, November 15, 2008 4:01 AM