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

本文关键字:用户 详细信息 获取 Directory 何使用 LDAP Active | 更新日期: 2023-09-27 18:03:34

我需要使用LDAP从Active directory获取所有用户的详细信息。下面的代码确实给出了Samaccountname为"Administrator",但没有给出每个用户的详细信息,也没有在列表中找到邮件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);  
}

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

最近我一直在研究LDAP。我需要从AD找到所有的信息。因此,我编写了一些帮助类来查找它们。下面是一些例子。

我写了5个类。见下文

ActiveDirectoryHelper.cs

public class ActiveDirectoryHelper
{
    private DirectoryEntry _directoryEntry = null;
    private DirectoryEntry SearchRoot
    {
        get
        {
            if (_directoryEntry == null)
            {
                using (HostingEnvironment.Impersonate())
                {
                    _directoryEntry = new DirectoryEntry(LDAPPath);//, LDAPUser, LDAPPassword, AuthenticationTypes.Secure);
                }
            }
            return _directoryEntry;
        }
    }
    private String LDAPPath
    {
        get
        {
            return ConfigurationManager.AppSettings["LDAPPath"];
        }
    }
    //private String LDAPUser
    //{
    //    get
    //    {
    //        return ConfigurationManager.AppSettings["LDAPUser"];
    //    }
    //}
    //private String LDAPPassword
    //{
    //    get
    //    {
    //        return ConfigurationManager.AppSettings["LDAPPassword"];
    //    }
    //}
    private String LDAPDomain
    {
        get
        {
            return ConfigurationManager.AppSettings["LDAPDomain"];
        }
    }
    internal ADUserDetail GetUserByFullName(String userName)
    {
        try
        {
            using (HostingEnvironment.Impersonate())
            {
                _directoryEntry = null;
                DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
                directorySearch.Filter = "(&(objectClass=user)(cn=" + userName + "))";
                SearchResult results = directorySearch.FindOne();
                if (results != null)
                {
                    DirectoryEntry user = new DirectoryEntry(results.Path);// LDAPUser, LDAPPassword);
                    return ADUserDetail.GetUser(user);
                }
                else
                {
                    return null;
                }
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    public ADUserDetail GetUserByLoginName(String userName)
    {

        try
        {
            using (HostingEnvironment.Impersonate())
            {
                // This code runs as the application pool user

                _directoryEntry = null;
                string nn = "LDAP://PRIME.local/DC=PRIME,DC=local";
                DirectoryEntry SearchRoot2 = new DirectoryEntry(nn);
                DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
                directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))";
                SearchResult results = directorySearch.FindOne();
                if (results != null)
                {
                    DirectoryEntry user = new DirectoryEntry(results.Path);//, LDAPUser, LDAPPassword);
                    return ADUserDetail.GetUser(user);
                }
                return null;
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    public ADUserDetail GetUserDetailsByFullName(String FirstName, String MiddleName, String LastName)
    {
        //givenName
        //    initials
        //    sn
        //(initials=" + MiddleName + ")(sn=" + LastName + ")
        try
        {
            using (HostingEnvironment.Impersonate())
            {
                _directoryEntry = null;
                DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
                //directorySearch.Filter = "(&(objectClass=user)(givenName=" + FirstName + ") ())";
                if (FirstName != "" && MiddleName != "" && LastName != "")
                {
                    directorySearch.Filter = "(&(objectClass=user)(givenName=" + FirstName + ")(initials=" + MiddleName + ")(sn=" + LastName + "))";
                }
                else if (FirstName != "" && MiddleName != "" && LastName == "")
                {
                    directorySearch.Filter = "(&(objectClass=user)(givenName=" + FirstName + ")(initials=" + MiddleName + "))";
                }
                else if (FirstName != "" && MiddleName == "" && LastName == "")
                {
                    directorySearch.Filter = "(&(objectClass=user)(givenName=" + FirstName + "))";
                }
                else if (FirstName != "" && MiddleName == "" && LastName != "")
                {
                    directorySearch.Filter = "(&(objectClass=user)(givenName=" + FirstName + ")(sn=" + LastName + "))";
                }
                else if (FirstName == "" && MiddleName != "" && LastName != "")
                {
                    directorySearch.Filter = "(&(objectClass=user)(initials=" + MiddleName + ")(sn=" + LastName + "))";
                }
                SearchResult results = directorySearch.FindOne();
                if (results != null)
                {
                    DirectoryEntry user = new DirectoryEntry(results.Path);//, LDAPUser, LDAPPassword);
                    return ADUserDetail.GetUser(user);
                }
                return null;
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    /// <summary>
    /// This function will take a DL or Group name and return list of users
    /// </summary>
    /// <param name="groupName"></param>
    /// <returns></returns>
    public List<ADUserDetail> GetUserFromGroup(String groupName)
    {
        List<ADUserDetail> userlist = new List<ADUserDetail>();
        try
        {
            using (HostingEnvironment.Impersonate())
            {
                _directoryEntry = null;
                DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
                directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))";
                SearchResult results = directorySearch.FindOne();
                if (results != null)
                {
                    DirectoryEntry deGroup = new DirectoryEntry(results.Path);//, LDAPUser, LDAPPassword);
                    System.DirectoryServices.PropertyCollection pColl = deGroup.Properties;
                    int count = pColl["member"].Count;

                    for (int i = 0; i < count; i++)
                    {
                        string respath = results.Path;
                        string[] pathnavigate = respath.Split("CN".ToCharArray());
                        respath = pathnavigate[0];
                        string objpath = pColl["member"][i].ToString();
                        string path = respath + objpath;

                        DirectoryEntry user = new DirectoryEntry(path);//, LDAPUser, LDAPPassword);
                        ADUserDetail userobj = ADUserDetail.GetUser(user);
                        userlist.Add(userobj);
                        user.Close();
                    }
                }
                return userlist;
            }
        }
        catch (Exception ex)
        {
            return userlist;
        }
    }
    #region Get user with First Name
    public List<ADUserDetail> GetUsersByFirstName(string fName)
    {
        using (HostingEnvironment.Impersonate())
        {
            //UserProfile user;
            List<ADUserDetail> userlist = new List<ADUserDetail>();
            string filter = "";
            _directoryEntry = null;
            DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
            directorySearch.Asynchronous = true;
            directorySearch.CacheResults = true;
            filter = string.Format("(givenName={0}*", fName);
            //            filter = "(&(objectClass=user)(objectCategory=person)(givenName="+fName+ "*))";

            directorySearch.Filter = filter;
            SearchResultCollection userCollection = directorySearch.FindAll();
            foreach (SearchResult users in userCollection)
            {
                DirectoryEntry userEntry = new DirectoryEntry(users.Path);//, LDAPUser, LDAPPassword);
                ADUserDetail userInfo = ADUserDetail.GetUser(userEntry);
                userlist.Add(userInfo);
            }
            directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + fName + "*))";
            SearchResultCollection results = directorySearch.FindAll();
            if (results != null)
            {
                foreach (SearchResult r in results)
                {
                    DirectoryEntry deGroup = new DirectoryEntry(r.Path);//, LDAPUser, LDAPPassword);
                    ADUserDetail agroup = ADUserDetail.GetUser(deGroup);
                    userlist.Add(agroup);
                }
            }
            return userlist;
        }
    }
    #endregion

    #region AddUserToGroup
    public bool AddUserToGroup(string userlogin, string groupName)
    {
        try
        {
            using (HostingEnvironment.Impersonate())
            {
                _directoryEntry = null;
                ADManager admanager = new ADManager(LDAPDomain);//, LDAPUser, LDAPPassword);
                admanager.AddUserToGroup(userlogin, groupName);
                return true;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    #endregion
    #region RemoveUserToGroup
    public bool RemoveUserToGroup(string userlogin, string groupName)
    {
        try
        {
            using (HostingEnvironment.Impersonate())
            {
                _directoryEntry = null;
                ADManager admanager = new ADManager("xxx");// LDAPUser, LDAPPassword);
                admanager.RemoveUserFromGroup(userlogin, groupName);
                return true;
            }
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    #endregion
}

AccountManagementExtensions.cs

public static class AccountManagementExtensions
{
    public static String GetProperty(this Principal principal, String property)
    {
        DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
        if (directoryEntry.Properties.Contains(property))
            return directoryEntry.Properties[property].Value.ToString();
        else
            return String.Empty;
    }
    public static String GetCompany(this Principal principal)
    {
        return principal.GetProperty("company");
    }
    public static String GetDepartment(this Principal principal)
    {
        return principal.GetProperty("department");
    }
}

ADManager.cs

public class ADManager
{
    PrincipalContext context;
    public ADManager()
    {
        context = new PrincipalContext(ContextType.Machine, "xxx", "xxx", "xxx");
    }

    public ADManager(string domain, string container)
    {
        context = new PrincipalContext(ContextType.Domain, domain, container);
    }
    public ADManager(string domain)//, string username, string password)
    {
        context = new PrincipalContext(ContextType.Domain);//, username, password);
    }
    public bool AddUserToGroup(string userName, string groupName)
    {
        bool done = false;
        GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);
        if (group == null)
        {
            group = new GroupPrincipal(context, groupName);
        }
        UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);
        if (user != null & group != null)
        {
            group.Members.Add(user);
            group.Save();
            done = (user.IsMemberOf(group));
        }
        return done;
    }

    public bool RemoveUserFromGroup(string userName, string groupName)
    {
        bool done = false;
        UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);
        GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);
        if (user != null & group != null)
        {
            group.Members.Remove(user);
            group.Save();
            done = !(user.IsMemberOf(group));
        }
        return done;
    }
}

ADProperties.cs

public static class ADProperties
{
    public const String OBJECTCLASS = "objectClass";
    public const String CONTAINERNAME = "cn";
    public const String LASTNAME = "sn";
    public const String COUNTRYNOTATION = "c";
    public const String CITY = "l";
    public const String STATE = "st";
    public const String TITLE = "title";
    public const String POSTALCODE = "postalCode";
    public const String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName";
    public const String FIRSTNAME = "givenName";
    public const String MIDDLENAME = "initials";
    public const String DISTINGUISHEDNAME = "distinguishedName";
    public const String INSTANCETYPE = "instanceType";
    public const String WHENCREATED = "whenCreated";
    public const String WHENCHANGED = "whenChanged";
    public const String DISPLAYNAME = "displayName";
    public const String USNCREATED = "uSNCreated";
    public const String MEMBEROF = "memberOf";
    public const String USNCHANGED = "uSNChanged";
    public const String COUNTRY = "co";
    public const String DEPARTMENT = "department";
    public const String COMPANY = "company";
    public const String PROXYADDRESSES = "proxyAddresses";
    public const String STREETADDRESS = "streetAddress";
    public const String DIRECTREPORTS = "directReports";
    public const String NAME = "name";
    public const String OBJECTGUID = "objectGUID";
    public const String USERACCOUNTCONTROL = "userAccountControl";
    public const String BADPWDCOUNT = "badPwdCount";
    public const String CODEPAGE = "codePage";
    public const String COUNTRYCODE = "countryCode";
    public const String BADPASSWORDTIME = "badPasswordTime";
    public const String LASTLOGOFF = "lastLogoff";
    public const String LASTLOGON = "lastLogon";
    public const String PWDLASTSET = "pwdLastSet";
    public const String PRIMARYGROUPID = "primaryGroupID";
    public const String OBJECTSID = "objectSid";
    public const String ADMINCOUNT = "adminCount";
    public const String ACCOUNTEXPIRES = "accountExpires";
    public const String LOGONCOUNT = "logonCount";
    public const String LOGINNAME = "sAMAccountName";
    public const String SAMACCOUNTTYPE = "sAMAccountType";
    public const String SHOWINADDRESSBOOK = "showInAddressBook";
    public const String LEGACYEXCHANGEDN = "legacyExchangeDN";
    public const String USERPRINCIPALNAME = "userPrincipalName";
    public const String EXTENSION = "ipPhone";
    public const String SERVICEPRINCIPALNAME = "servicePrincipalName";
    public const String OBJECTCATEGORY = "objectCategory";
    public const String DSCOREPROPAGATIONDATA = "dSCorePropagationData";
    public const String LASTLOGONTIMESTAMP = "lastLogonTimestamp";
    public const String EMAILADDRESS = "mail";
    public const String MANAGER = "manager";
    public const String MOBILE = "mobile";
    public const String PAGER = "pager";
    public const String FAX = "facsimileTelephoneNumber";
    public const String HOMEPHONE = "homePhone";
    public const String MSEXCHUSERACCOUNTCONTROL = "msExchUserAccountControl";
    public const String MDBUSEDEFAULTS = "mDBUseDefaults";
    public const String MSEXCHMAILBOXSECURITYDESCRIPTOR = "msExchMailboxSecurityDescriptor";
    public const String HOMEMDB = "homeMDB";
    public const String MSEXCHPOLICIESINCLUDED = "msExchPoliciesIncluded";
    public const String HOMEMTA = "homeMTA";
    public const String MSEXCHRECIPIENTTYPEDETAILS = "msExchRecipientTypeDetails";
    public const String MAILNICKNAME = "mailNickname";
    public const String MSEXCHHOMESERVERNAME = "msExchHomeServerName";
    public const String MSEXCHVERSION = "msExchVersion";
    public const String MSEXCHRECIPIENTDISPLAYTYPE = "msExchRecipientDisplayType";
    public const String MSEXCHMAILBOXGUID = "msExchMailboxGuid";
    public const String NTSECURITYDESCRIPTOR = "nTSecurityDescriptor";
}

ADUserDetail.cs

public class ADUserDetail
{
    private String _firstName;
    private String _middleName;
    private String _lastName;
    private String _loginName;
    private String _loginNameWithDomain;
    private String _streetAddress;
    private String _city;
    private String _state;
    private String _postalCode;
    private String _country;
    private String _homePhone;
    private String _extension;
    private String _mobile;
    private String _fax;
    private String _emailAddress;
    private String _title;
    private String _company;
    private String _manager;
    private String _managerName;
    private String _department;
    public String Department
    {
        get { return _department; }
    }
    public String FirstName
    {
        get { return _firstName; }
    }
    public String MiddleName
    {
        get { return _middleName; }
    }
    public String LastName
    {
        get { return _lastName; }
    }
    public String LoginName
    {
        get { return _loginName; }
    }
    public String LoginNameWithDomain
    {
        get { return _loginNameWithDomain; }
    }
    public String StreetAddress
    {
        get { return _streetAddress; }
    }
    public String City
    {
        get { return _city; }
    }
    public String State
    {
        get { return _state; }
    }
    public String PostalCode
    {
        get { return _postalCode; }
    }
    public String Country
    {
        get { return _country; }
    }
    public String HomePhone
    {
        get { return _homePhone; }
    }
    public String Extension
    {
        get { return _extension; }
    }
    public String Mobile
    {
        get { return _mobile; }
    }
    public String Fax
    {
        get { return _fax; }
    }
    public String EmailAddress
    {
        get { return _emailAddress; }
    }
    public String Title
    {
        get { return _title; }
    }
    public String Company
    {
        get { return _company; }
    }
    public ADUserDetail Manager
    {
        get
        {
            if (!String.IsNullOrEmpty(_managerName))
            {
                ActiveDirectoryHelper ad = new ActiveDirectoryHelper();
                return ad.GetUserByFullName(_managerName);
            }
            return null;
        }
    }
    public String ManagerName
    {
        get { return _managerName; }
    }

    private ADUserDetail(DirectoryEntry directoryUser)
    {
        String domainAddress;
        String domainName;
        _firstName = GetProperty(directoryUser, ADProperties.FIRSTNAME);
        _middleName = GetProperty(directoryUser, ADProperties.MIDDLENAME);
        _lastName = GetProperty(directoryUser, ADProperties.LASTNAME);
        _loginName = GetProperty(directoryUser, ADProperties.LOGINNAME);
        String userPrincipalName = GetProperty(directoryUser, ADProperties.USERPRINCIPALNAME);
        if (!string.IsNullOrEmpty(userPrincipalName))
        {
            domainAddress = userPrincipalName.Split('@')[1];
        }
        else
        {
            domainAddress = String.Empty;
        }
        if (!string.IsNullOrEmpty(domainAddress))
        {
            domainName = domainAddress.Split('.').First();
        }
        else
        {
            domainName = String.Empty;
        }
        _loginNameWithDomain = String.Format(@"{0}'{1}", domainName, _loginName);
        _streetAddress = GetProperty(directoryUser, ADProperties.STREETADDRESS);
        _city = GetProperty(directoryUser, ADProperties.CITY);
        _state = GetProperty(directoryUser, ADProperties.STATE);
        _postalCode = GetProperty(directoryUser, ADProperties.POSTALCODE);
        _country = GetProperty(directoryUser, ADProperties.COUNTRY);
        _company = GetProperty(directoryUser, ADProperties.COMPANY);
        _department = GetProperty(directoryUser, ADProperties.DEPARTMENT);
        _homePhone = GetProperty(directoryUser, ADProperties.HOMEPHONE);
        _extension = GetProperty(directoryUser, ADProperties.EXTENSION);
        _mobile = GetProperty(directoryUser, ADProperties.MOBILE);
        _fax = GetProperty(directoryUser, ADProperties.FAX);
        _emailAddress = GetProperty(directoryUser, ADProperties.EMAILADDRESS);
        _title = GetProperty(directoryUser, ADProperties.TITLE);
        _manager = GetProperty(directoryUser, ADProperties.MANAGER);
        if (!String.IsNullOrEmpty(_manager))
        {
            String[] managerArray = _manager.Split(',');
            _managerName = managerArray[0].Replace("CN=", "");
        }
    }

    private static String GetProperty(DirectoryEntry userDetail, String propertyName)
    {
        if (userDetail.Properties.Contains(propertyName))
        {
            return userDetail.Properties[propertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }
    public static ADUserDetail GetUser(DirectoryEntry directoryUser)
    {
        return new ADUserDetail(directoryUser);
    }
}

你只需要在AppSettings部分添加你的LDAP地址web。配置文件。如果您需要,您可以添加用户名或密码。否则,直接添加LDAP地址。


<appSettings>
<add key="LDAPPassword" value="" />
<add key="LDAPPath" value="" />
<add key="LDAPUser" value="" />
<add key="LDAPDomain" value="" />
</appSettings>

在项目中包含这些类。现在您可以从活动目录中获得所有信息。在"ActiveDirectoryHelper.cs"上有一些方法。您可以使用它们检索信息。

尝试查看"mail"属性(而不是"mail")

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

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

上个月,项目经理要求我从Active directory中查找所有用户信息,以及哪些字段缺少特定用户的信息。我试图在互联网上搜索有关。net活动目录示例的信息,我无法在网上找到很多信息,这促使我写了一篇关于这个主题的文章。

在本文中,我将解释如何使用Active Directory类并从组件类中检索数据。您可以剪切和过去下面的代码行并执行它,但您需要在目录入口构造器中传递域名。下面的例子取自我开发的一个项目,并为便于理解而进行了修改。

我假设您在使用这个示例之前对活动目录有一个大致的了解。步骤1:

Add System.DirectoryServices.Dll (from Project Add reference)

系统。DirectoryServices提供了从托管代码轻松访问活动目录的功能。这个命名空间包含两个组件类,DirectoryEntry和DirectorySearcher。步骤2:

Using System.DirectoryServices

目录入口类:该类封装活动目录层次结构中的节点或对象。使用这个类绑定到对象、读取属性和更新属性。步骤3:

DirectoryEntry entry = new DirectoryEntry("LDAP://DomainName");

Directory Searcher:它将对活动目录层次结构执行查询步骤4:

DirectorySearcher Dsearch = new DirectorySearcher(entry);

第五步:隐藏复制代码

String Name="Richmond";

Filter属性支持对活动目录的信息进行全部过滤。