Different approaches for finding users within Active Directory

Posted by EvilDr on Stack Overflow See other posts from Stack Overflow or by EvilDr
Published on 2012-11-26T16:33:57Z Indexed on 2012/11/27 5:04 UTC
Read the original article Hit count: 204

Filed under:
|
|
|

I'm a newbie to AD programming, but after a couple of weeks of research have found the following three ways to search for users in Active Directory using the account name as the search parameter:

Option 1 - FindByIdentity

Dim ctx As New PrincipalContext(ContextType.Domain, Environment.MachineName)
Dim u As UserPrincipal = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "MYDOMAIN\Administrator")
If u Is Nothing Then
    Trace.Warn("No user found.")
Else
    Trace.Warn("Name=" & u.Name)
    Trace.Warn("DisplayName=" & u.DisplayName)
    Trace.Warn("DistinguishedName=" & u.DistinguishedName)
    Trace.Warn("EmployeeId=" & u.EmployeeId)
    Trace.Warn("EmailAddress=" & u.EmailAddress)
End If

Option 2 - DirectorySearcher

Dim connPath As String = "LDAP://" & Environment.MachineName
Dim de As New DirectoryEntry(connPath)
Dim ds As New DirectorySearcher(de)
ds.Filter = String.Format("(&(objectClass=user)(anr={0}))", Split(User.Identity.Name, "\")(1))
ds.PropertiesToLoad.Add("name")
ds.PropertiesToLoad.Add("displayName")
ds.PropertiesToLoad.Add("distinguishedName")
ds.PropertiesToLoad.Add("employeeId")
ds.PropertiesToLoad.Add("mail")
Dim src As SearchResult = ds.FindOne()
If src Is Nothing Then
    Trace.Warn("No user found.")
Else
    For Each propertyKey As String In src.Properties.PropertyNames
        Dim valueCollection As ResultPropertyValueCollection = src.Properties(propertyKey)
        For Each propertyValue As Object In valueCollection
            Trace.Warn(propertyKey & "=" & propertyValue.ToString)
        Next
    Next
End If

Option 3 - PrincipalSearcher

Dim ctx2 As New PrincipalContext(ContextType.Domain, Environment.MachineName)
Dim sp As New UserPrincipal(ctx2)
sp.SamAccountName = "MYDOMAIN\Administrator"
Dim s As New PrincipalSearcher
s.QueryFilter = sp
Dim p2 As UserPrincipal = s.FindOne()
If p2 Is Nothing Then
    Trace.Warn("No user found.")
Else
    Trace.Warn(p2.Name)
    Trace.Warn(p2.DisplayName)
    Trace.Warn(p2.DistinguishedName)
    Trace.Warn(p2.EmployeeId)
    Trace.Warn(p2.EmailAddress)
End If

All three of these methods return the same results, but I was wondering if any particular method is better or worse than the others?

Option 1 or 3 seem to be the best as they provide strongly-typed property names, but I might be wrong? My overall objective is to find a single user within AD based on the user principal value passed via the web browser when using Windows Authentication on a site (e.g. "MYDOMAIN\MyUserAccountName")

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about vb.net