Search the directories : Search « Directory Services « C# / CSharp Tutorial






using System;
using System.DirectoryServices;

public class MainClass {
  static void Main(string[] args) {
    try
    {
      DirectoryEntry oRoot = new DirectoryEntry("LDAP://RootDSE");
      string searchOU = (string)oRoot.Properties["defaultnamingcontext"].Value;
      DirectoryEntry de = new DirectoryEntry("LDAP://CN=Users," + searchOU); 
      Console.WriteLine(oRoot.Name);
      oRoot.Close();
        
      DirectorySearcher search = new DirectorySearcher(de);
      search.Filter = "(CN=Administrator)";
      search.PropertiesToLoad.Add("distinguishedName");
      SearchResultCollection results = search.FindAll();
      
      string strRet="Not Found";
      foreach(SearchResult result in results)
      {
        DirectoryEntry data = result.GetDirectoryEntry();
        strRet = (string)data.Properties["distinguishedName"].Value;
        Console.WriteLine(strRet);
        data.Close();
      }
      de.Close();
      results.Dispose();
    }catch(Exception e){
      Console.WriteLine( e.Message);
    }
  }
}








34.7.Search
34.7.1.Simple Search
34.7.2.Search the directories