Querying Active Directory for Domain Names

When creating users through the CRM SDK you must specify the domain name.  However in some situations you may not have the user’s domain name if the environment has multiple Active Directory domains within a forest.

Here is a code snippet that queries Active Directory for their name.

 

   1: public string GetUserName(string username)

   2: {

   3:     string retval = string.Empty;

   4:  

   5:     var currentForest = Forest.GetCurrentForest();

   6:     var globalCatalog = currentForest.FindGlobalCatalog();

   7:  

   8:     using (var searcher = globalCatalog.GetDirectorySearcher())

   9:     {

  10:         using (var de = new DirectoryEntry(searcher.SearchRoot.Path))

  11:         {

  12:             using (var ds = new DirectorySearcher(de))

  13:             {

  14:                ds.ReferralChasing = ReferralChasingOption.All;

  15:  

  16:                ds.Filter = String.Format("(&(objectCategory=person)(objectClass=user)(SAMAccountName={0}))", username);

  17:                ds.PropertiesToLoad.Add("UserPrincipalName");

  18:  

  19:                SearchResult result = ds.FindOne();

  20:  

  21:                 if(result != null)

  22:                 {

  23:                     retval = result.Properties["UserPrincipalName"][0].ToString();

  24:                 }

  25:             }

  26:         }

  27:     }

  28:  

  29:     return retval;

  30: }

 

Thanks to Chris for the code!

Hope this helps!

// Dave

This entry was posted in Development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *