Tuesday, May 1, 2018

Check If An Email Exists In Active Directory Domain

Good afternoon gents!

Here's a method on checking if an email exists in an Active Directory Domain given the format of an email FirstName.LastName@yourcompanyname.com. If the format of your company email is different from the one presented, just change the logic of the code to extract the family name.
/* 
  Email Format: Gregory.Esguerra@abcbusiness.com
*/
private bool CheckIfEmailExistsInDomain(string email)
{
 string searchName = string.Empty;
 searchName = email.Substring(email.IndexOf('.') + 1, (email.IndexOf('@')-1) - email.IndexOf('.'));
 using (var context = new PrincipalContext(ContextType.Domain, "abcbusiness.corp"))
 {
  using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
  {
   PrincipalSearchResult<Principal> allPrincipal = searcher.FindAll();
   List<Principal> principalObjects = allPrincipal.Where(t => t.Name.Contains(ToUpperFirstLetter(searchName))).ToList();

   if (principalObjects.Count > 0 && principalObjects != null)
   {
    foreach (var principalObject in principalObjects)
    {
     DirectoryEntry dEntry = principalObject.GetUnderlyingObject() as DirectoryEntry;
     if (dEntry.Properties["mail"].Value != null)
     {
      if (dEntry.Properties["mail"].Value.ToString().Equals(email, StringComparison.OrdinalIgnoreCase))
      {
       return true;
      }
     }
    }
   }
   else
   {
    return false;
   }
  }
 }

 return false;
}

0 comments:

Post a Comment