Private Function GetPrimaryGroupName(ByVal SearcherObject As DirectorySearcher, ByVal User As SearchResult) As String
Try
Using Domain As DirectoryEntry = ActiveDirectory.Domain.GetCurrentDomain.GetDirectoryEntry
Dim GroupSID As New Security.Principal.SecurityIdentifier(New Security.Principal.SecurityIdentifier(DirectCast(Domain.Properties("objectSid").Value, Byte()), 0).ToString & "-" & CStr(User.Properties("primaryGroupID")(0)))
Dim GroupSIDString As New System.Text.StringBuilder
Dim GroupSIDBytes(GroupSID.BinaryLength – 1) As Byte
GroupSID.GetBinaryForm(GroupSIDBytes, 0)
For i As Integer = 0 To GroupSIDBytes.Length – 1
GroupSIDString.Append("\" & Hex(GroupSIDBytes(i)).PadLeft(2, "0"c))
Next
SearcherObject.Filter = "(objectSid=" & GroupSIDString.ToString & ")"
Dim GroupSearchResult As SearchResult = SearcherObject.FindOne
If Not GroupSearchResult Is Nothing Then
Return GetGroupNameFromPath(GroupSearchResult.Path)
Else
Throw New ApplicationException("Failed to locate primary group – no results returned for the LDAP query " & SearcherObject.Filter)
End If
End Using
Catch ex As Exception
Throw New ApplicationException("Error getting primary group: " & ex.Message.Trim)
End Try
End Function
Private Function GetGroupNameFromPath(ByVal Path As String) As String
Dim GroupName As String = Path.Replace("LDAP://", String.Empty).Remove(0, 3)
Dim SeparatorIndex As Integer = 0
For i As Integer = 0 To GroupName.Length – 1
If GroupName(i) = ","c AndAlso Not GroupName(i – 1) = "\"c Then
SeparatorIndex = i
Exit For
End If
Next
GroupName = GroupName.Remove(SeparatorIndex)
Return GroupName.Replace("\,", ",").Replace("\\", "\").Replace("\+", "+").Replace("\""", """").Replace("\<", "<").Replace("\>", ">").Replace("\;", ";")
End Function