微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何使用LDAP从Active Directory获取所有用户的详细信息

我需要使用LDAP从Active Directory获取所有用户的详细信息.以下代码确实将Samaccountname作为“管理员”,但不是每个用户的详细信息,并且在列表中找不到邮件ID.请帮助.

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());
            }
        }

找到解决方

这是我的代码

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);  

}

解决方法

尝试查看“mail”属性(不是“Mail”).

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

这是AD用户属性参考(如果您想获得其他内容):http://www.kouti.com/tables/userattributes.htm

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐