簡體   English   中英

從LDAP / Active Directory搜索結果中讀取屬性的最快方法

[英]Fastest way of reading a property from LDAP/Active Directory Search results

using (DirectoryEntry rootEntry = new DirectoryEntry(ConfigurationKeys.Ldap, string.Empty, string.Empty, AuthenticationTypes.None))
{
    using (DirectorySearcher adSearch = new DirectorySearcher(rootEntry))
    {
        adSearch.SearchScope = SearchScope.Subtree;
        adSearch.PropertiesToLoad.Add("givenname");
        adSearch.PropertiesToLoad.Add("mail");

        adSearch.Filter = "(mail=myemail@mydomain.org)";
        SearchResult adSearchResult = adSearch.FindOne();
    }
}

從上面的示例中,檢索屬性“givenname”並將其存儲到字符串變量中的最有效方法是什么?

由於您要在搜索中加載的屬性列表中包含該屬性,因此只需在搜索結果中訪問該屬性:

using (DirectoryEntry rootEntry = new DirectoryEntry(ConfigurationKeys.Ldap, string.Empty, string.Empty, AuthenticationTypes.None))
{
    using (DirectorySearcher adSearch = new DirectorySearcher(rootEntry))
    {
        adSearch.SearchScope = SearchScope.Subtree;
        adSearch.PropertiesToLoad.Add("givenname");
        adSearch.PropertiesToLoad.Add("mail");

        adSearch.Filter = "(mail=myemail@mydomain.org)";

        SearchResult adSearchResult = adSearch.FindOne();

        // make sure the adSearchResult is not null
        // and the "givenName" property is not null (could be empty / null)
        if(adSearchResult != null && adSearchResult.Properties["givenName"] != null) 
        {
            // make sure the givenName property contains at least one string value
            if (adSearchResult.Properties["givenName"].Count > 0)
            {
               string givenName = adSearchResult.Properties["givenName"][0].ToString();
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM