DirectoryEntry entry = new DirectoryEntry("LDAP://DC=example,DC=com"); DirectorySearcher searcher = new DirectorySearcher(entry); searcher.Filter = "(objectClass=user)"; SearchResultCollection results = searcher.FindAll(); foreach(SearchResult result in results) { Console.WriteLine(result.Path); }
DirectoryEntry entry = new DirectoryEntry("LDAP://DC=example,DC=com"); DirectorySearcher searcher = new DirectorySearcher(entry); searcher.Filter = "(&(objectClass=user)(sAMAccountName=john.doe))"; SearchResult result = searcher.FindOne(); if(result != null) { Console.WriteLine(result.Path); }In this example, we create a DirectoryEntry object and a DirectorySearcher object as before. However, this time we set the Filter property to search for a specific user with the sAMAccountName "john.doe". We then call the FindOne method to get a single SearchResult object, which we check for null to ensure that the user was found. These examples demonstrate how to use the DirectorySearcher class in C# to search for objects in a directory. The package library for this class is System.DirectoryServices.dll.