DirectorySearcher in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes the DirectorySearcher control


DirectorySearcher

This object is performing queries against an Active Directory Domain Services hierarchy.

    Imports System.DirectoryServices

    ' this sample code reads all the user from Active Directory

    Dim entry As DirectoryEntry = Nothing
    Dim searcher As DirectorySearcher = Nothing

    ' create a directory entry object with current application context user
    ' we pass username and password as nothing to make it takes the current user credentials
    entry = New DirectoryEntry("LDAP path here", Nothing, Nothing, AuthenticationTypes.Secure)

    ' create a searcher for this directory entry.
    searcher = New DirectorySearcher(entry)

    ' specify the filter
    searcher.Filter = "(&(objectCategory=person)(objectClass=user))"

    ' specify the properties to be loaded
    searcher.PropertiesToLoad.Add("mail")
    searcher.PropertiesToLoad.Add("name")
    searcher.PropertiesToLoad.Add("userPrincipalName")

    ' load results into search result collection
    Dim result As SearchResultCollection = searcher.FindAll()

    ' loop through the collection
    For Each res As SearchResult In result
        ' get the properties
        Console.WriteLine(res.Properties("mail").Item(0).ToString)
        Console.WriteLine(res.Properties("name").Item(0).ToString)
        Console.WriteLine(res.Properties("userPrincipalName").Item(0).ToString)
    Next

    ' release the resources
    entry.Dispose()
    searcher.Dispose()
    result.Dispose()

Previous Lesson | Next Lesson


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.