Querying Active Directory

A while ago i wanted to figure out which demo accounts i had already created in my Active Directory. Since i was smart enough to give them all a description ‘Demo User’ this was easily done as following:

using( DirectoryEntry directoryEntry = new DirectoryEntry() )
{
 using( DirectorySearcher directorySearcher = new DirectorySearcher() )
 {
  directorySearcher.Filter = "(&(objectClass=user)(description=Demo User))";
  directorySearcher.SearchScope = SearchScope.Subtree;
  directorySearcher.Sort = new SortOption("displayname", SortDirection.Ascending );

  SearchResultCollection results = directorySearcher.FindAll();
  foreach( SearchResult result in results )
  {
   ResultPropertyCollection propertyCollection = result.Properties;
   Console.WriteLine( "{0}: {1}", propertyCollection["displayname"][0].ToString(), propertyCollection["description"][0].ToString() );
   }
  }
}

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>