How to Search User in Active Directory using LDAP in Asp.net C#

故事扮演 提交于 2021-02-07 04:13:24

问题


How can I fetch all the record from my Active Directory Server in asp.net c#?


回答1:


Make a connection string in LDAP providing username and Password which can communicate with the server and have Administrator rights.

Suppose DC is me.com and username and password are the password of that user Id which is having Administrator rights.

   DirectoryEntry rootDSE = rootDSE = new DirectoryEntry("LDAP://OU="",OU=" ",dc="me",dc=com", username, password);

    DirectorySearcher search = new DirectorySearcher(rootDSE);

    search.PageSize = 1001;// To Pull up more than 100 records.

     search.Filter = "(&(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";//UserAccountControl will only Include Non-Disabled Users.
      SearchResultCollection result = search.FindAll();

         foreach (SearchResult item in result)
        {
            if (item.Properties["cn"].Count > 0)
            {
                DisplayName = item.Properties["cn"][0].ToString();
            }
            if (item.Properties["mail"].Count > 0)
            {
                EmailAddress = item.Properties["mail"][0].ToString();
            }
            if (item.Properties["SamAccountName"].Count > 0)
            {
                DomainName = item.Properties["SamAccountName"][0].ToString();
            }
            if (item.Properties["department"].Count > 0)
            {
                Department = item.Properties["department"][0].ToString();
            }
            if (item.Properties["title"].Count > 0)
            {
                title = item.Properties["title"][0].ToString();
            }
            if (item.Properties["company"].Count > 0)
            {
                company = item.Properties["company"][0].ToString();
            }
            if (item.Properties["DistinguishedName"].Count > 0)
            {
                memberof = item.Properties["DistinguishedName"][0].ToString();
            }
            if (item.Properties["AccountExpirationDate"].Count > 0)
            {
                string aaa = item.Properties["AccountExpirationDate"][0].ToString();
            }

              dt.Rows.Add(DisplayName, EmailAddress, DomainName, Department, title, company, memberof);
             DisplayName = string.Empty;
             EmailAddress = string.Empty;
             DomainName = string.Empty;
             Department = string.Empty;
             title = string.Empty;
             company = string.Empty;
             memberof = string.Empty;

               rootDSE.Dispose();

In this way we can Pull up all the records from our Domain Server.



来源:https://stackoverflow.com/questions/12285196/how-to-search-user-in-active-directory-using-ldap-in-asp-net-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!