How to get all the user's details from Active Directory using LDAP

asp.net, c#, ldap

Solution

Try to look under "mail" property(not "Mail").

sb.AppendLine("Email = " + de.Properties["mail"].Value.ToString());

Here is AD user attributes reference(in case you would like to get something else): http://www.kouti.com/tables/userattributes.htm

Problem

I need to get all the user's details from Active directory using LDAP. The following code does gives `Samaccountname` as 'Administrator' but not each user's details and no mail ID is found in the list. Kindly Help. ``` string dominName = ConfigurationManager.AppSettings["DominName"].ToString(); string ldapPath = ConfigurationManager.AppSettings["ldapPath"].ToString(); if (!String.IsNullOrEmpty(dominName) && !String.IsNullOrEmpty(ldapPath)) { DirectoryEntry entry = new DirectoryEntry(ldapPath, txtUsername.Text.ToString().Trim(), txtPassword.Text.ToString().Trim()); try { Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(&(objectClass=user)(objectCategory=person))"; search.PropertiesToLoad.Add("samaccountname"); search.PropertiesToLoad.Add("mail"); search.PropertiesToLoad.Add("usergroup"); search.PropertiesToLoad.Add("displayname");//first name foreach (System.DirectoryServices.SearchResult resEnt in search.FindAll()) { System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry(); if (de.Properties["sAMAccountName"].Value != null && de.Properties["userAccountControl"].Value!=null) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Name = " + de.Properties["sAMAccountName"].Value.ToString()); sb.AppendLine("Email = " + de.Properties["Mail"].Value.ToString()); } } ``` Found Solution: Here is my code: ``` var userAccountControlValue = 0; int.TryParse(de.Properties["UserAccountControl"].Value.ToString(), out userAccountControlValue); var isAccountDisabled = Convert.ToBoolean(userAccountControlValue & 0x0002); var isNormalAccount = Convert.ToBoolean(userAccountControlValue & 0x0200); if (de.Properties["sAMAccountName"].Value != null && de.Properties["userAccountControl"].Value != null && de.Properties["userPrincipalName"].Value != null && !isAccountDisabled && isNormalAccount) { //Add Employee details from AD PaySlipPortal.Objects.Employee employee = new Employee(); employee.FirstName = de.Properties["givenName"].Value!=null?(string)de.Properties["givenName"].Value:""; employee.Email = de.Properties["userPrincipalName"].Value != null ? (string)de.Properties["userPrincipalName"].Value : ""; employee.LastName = de.Properties["sn"].Value != null ? (string)de.Properties["sn"].Value : ""; int deleteID= empBL.DeleteEmployee(employee.Email.Trim()); int empID = empBL.AddEmployee(employee); } ```

Original source