Hi all -
On startup of my program I would like it to verify the current user to active directory and basically determine if the user is in specific groups?
Has anyone done this or could point me in the right direction?
Printable View
Hi all -
On startup of my program I would like it to verify the current user to active directory and basically determine if the user is in specific groups?
Has anyone done this or could point me in the right direction?
Add a reference of System.DirectoryServices to your project then try this function
You can get the domain and user name from Environment objectCode:Public Function GetUserGroups(ByVal domain As String, ByVal usrName As String) As List(Of String)
Dim groupList As New List(Of String)
Dim adPath As String = "LDAP://CN=User,DC=" & domain & ",DC=com"
Dim search As DirectoryServices.DirectorySearcher = Nothing
Dim myResult As DirectoryServices.SearchResult = Nothing
Dim myGroup As DirectoryServices.ResultPropertyValueCollection = Nothing
Dim theGroup, strGroups() As String
Try
search = New DirectoryServices.DirectorySearcher(adPath)
search.Filter = "(SAMAccountName=" & usrName & ")"
search.PropertiesToLoad.Add("memberOf")
myResult = search.FindOne
myGroup = myResult.Properties.Item("memberOf")
'Extracting group names
groupList.Clear()
For i As Integer = 0 To myGroup.Count - 1
theGroup = myGroup.Item(i).ToString().Replace("CN=", "")
strGroups = theGroup.Split(","c)
If strGroups.Length > 1 Then
groupList.Add(strGroups(0).Trim())
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
Return Nothing
End Try
Return groupList
End Function
Something like this
Once you have the list of groups this user is member of, you can tell if he/she belongs to any specific group very easy.Code:Dim domain As String = Environment.UserDomainName
Dim user As String = Environment.UserName
Dim groups As List(Of String) = GetUserGroups(domain, user)
For Each grp As String In groups
MsgBox(grp)
Next
Thank you for the quick response, I will give this a try!