Get Email by sAMAccountName from LDAP


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

Uses LDAP to find EMail address by using the sAMAccountName.

Add System.DirectoryServices to references.


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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.