需要帮助在Active Directory中搜索多个属性

时间:2017-05-19 18:42:44

标签: c# active-directory

我正在为AD中的某个用户执行查询,并希望创建多个属性的列表。代码如下。当我执行searchResult.Properties [“manager”]或searchResult.Properties [“mail”]时,我得到了正确的结果。但是我如何搜索多个属性?

DirectoryEntry dEntry = new DirectoryEntry(path);    

                DirectorySearcher dSearcher = new DirectorySearcher(dEntry);                    

                dSearcher.Filter = "(&(ObjectClass=user)(samaccountname=mcavanaugh))";    

                sResults = dSearcher.FindAll();

                foreach (SearchResult searchResult in sResults)
                {
                    var sAMAccountName = searchResult.Properties["samaccountname"][0].ToString().ToLower();
                    if (sAMAccountName == "mcavanaugh")
                    {
                        //Right here is where i would select multiple ad properties
                        ResultPropertyValueCollection valueCollection = searchResult.Properties["manager, mail"];

                        foreach (Object propertyValue in valueCollection)
                        {
                            var PropertyName = (string)propertyValue.ToString();
                            testlist.Text = PropertyName;
                        }
                    }
                }

2 个答案:

答案 0 :(得分:0)

Properties属性没有一次访问多个属性的选项。混合来自不同属性的值似乎并不明智。您最好的解决方案是运行foreach两次,可能会创建一个DRY函数。

void addPropertyValues<T>(SearchResult sr, T testlist, string propName) {
    foreach (var pv in sr[propName]) {
        testlist.Text = pv.ToString();
    }
}
您可以在if

中使用

if (sAMAccountName == "mcavanaugh") {
    addPropertyValues(searchResult, testlist, "manager");
    addPropertyValues(searchResult, testlist, "mail");
}

答案 1 :(得分:0)

我最近一直在用这个。我找到了放置多个属性的位置并将它们放入数组中,并将它们分配给属性。到目前为止,它一直运作良好。 :

DirectoryEntry myLdapConnection = new DirectoryEntry("LDAP://DC=demo,DC=Com");

DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(sAMAccountName=" + username + ")";

string[] requiredProperties = new string[] { "cn", "Displayname", "Title", "Department", "l", "Homedirectory", "telephoneNumber", "lockoutTime", "badlogoncount", "passwordexpired", "badPasswordTime", "whenCreated", "sAMAccountName", "pwdLastSet", "thumbnailPhoto", "givenName", "sn", "mail", "msRTCSIP-PrimaryUserAddress", "distinguishedName", "manager" };


foreach(String property in requiredProperties)
search.PropertiesToLoad.Add(property);

//next code will output to a usertextbox that I had set up in a Form. You can convert to console.writeline

if (searchResult != null) {
    foreach(String property in requiredProperties)
    foreach(Object myCollection in searchResult.Properties[property])
    UserTextbox.Text += "\r\n" + (String.Format("{0,0} : {1} : {2}", property, myCollection.ToString(), myCollection.GetType().ToString()));
}