Get sAMAccountName by Email from LDAP


/ Published in: C#
Save to your folder(s)

Uses LDAP to find sAMAccountName by using the Email address.

Add System.DirectoryServices to references.


Copy this code and paste it in your HTML
  1. public static string GetSAMAccountNameByEmail(string email)
  2. {
  3. var oroot = new System.DirectoryServices.DirectoryEntry("LDAP://INVESTOR_AB");
  4. var osearcher = new System.DirectoryServices.DirectorySearcher(oroot);
  5. osearcher.Filter = string.Format("(&(mail={0}))", email);
  6. var oresult = osearcher.FindAll();
  7.  
  8. if (oresult.Count == 0) throw new InvalidOperationException(string.Format("Cannot find mail {0} in LDAP.", email));
  9. if (oresult.Count > 1) throw new InvalidOperationException(string.Format("There are {0} items with mail {1} in LDAP.", oresult.Count, email));
  10.  
  11. return oresult[0].Properties["sAMAccountName"][0].ToString();
  12. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.