14Jun VB.NET - Validate AD user
Yesterday I posted an article about how to list all the users in your Active Directory using VB.NET. This post is a lot smaller and will cover how to search your Active Directory for a specific user.
The function below will return true if the user is found, false if it’s not.
Public Function CheckIfUserExists(ByVal UserName As String) As Boolean
Dim dEntry As DirectoryEntry = ADHelper.GetDirectoryEntry()
Dim dEntrySearch As DirectorySearcher = New DirectorySearcher()
dEntrySearch.SearchRoot = dEntry
‘ tell the search that we only want to find object of type “user”
dEntrySearch.Filter = “(&(objectClass=user) (cn=” & UserName & “))”
Dim searchResult As SearchResultCollection = dEntrySearch.FindAll()
If searchResults.Count = 0 Then
Return False
Else
Return True
End If
End Function
Dim dEntry As DirectoryEntry = ADHelper.GetDirectoryEntry()
Dim dEntrySearch As DirectorySearcher = New DirectorySearcher()
dEntrySearch.SearchRoot = dEntry
‘ tell the search that we only want to find object of type “user”
dEntrySearch.Filter = “(&(objectClass=user) (cn=” & UserName & “))”
Dim searchResult As SearchResultCollection = dEntrySearch.FindAll()
If searchResults.Count = 0 Then
Return False
Else
Return True
End If
End Function
Don’t forget to add a reference to System.DirectoryServices if you’re going to use this function in a console application.

