获取分页DirectorySearcher的搜索结果总数

本文关键字:搜索结果 分页 DirectorySearcher 获取 | 更新日期: 2023-09-27 18:10:14

我正在使用DirectorySearch来搜索活动目录中的对象。我将VirtualListView属性设置为只返回几个值:

using System;
using System.DirectoryServices;
namespace Testbed
{
    internal class Testbed
    {
        private static void Main()
        {
            DoSearch();
            Console.ReadKey();
        }
        private static void DoSearch()
        {
            var entry = new DirectoryEntry("LDAP://server/DC=mydomain,DC=com", @"USERNAME", "PASSWORD");
            var searcher = new DirectorySearcher(entry)
            {
                PageSize = 0,
                SearchScope = SearchScope.Subtree,
                Filter = "(Description=J_*)",
                Sort = new SortOption("Description", SortDirection.Ascending),
                VirtualListView = new DirectoryVirtualListView(0, 9, 1)
            };
            SearchResultCollection results = searcher.FindAll();
            foreach (SearchResult result in results)
            {
                Console.WriteLine(result.Properties["Description"][0]);
            }
            Console.WriteLine("Found: " + results.Count);
        }
    }
}

是否有一种方法可以在AD中获得查询对象的总数,而无需根据PageSize(例如500)进行显式的DirectorySearch -"调用"?

获取分页DirectorySearcher的搜索结果总数

DirectoryVirtualListView类中有一个ApproximateTotal属性。您可以使用它,但请记住您应该在代码中的foreach块之后访问它。修改这一行:

Console.WriteLine("Found: " + results.Count);

:

Console.WriteLine("Found: " + searcher.VirtualListView.ApproximateTotal);

全部完成!

我遇到了VirtualListView。近似total返回零。我只在netcoreapp3.1中遇到过这个问题。

如果没有返回任何记录,我发现了一种方法来检索值

信贷https://github.com/dotnet/runtime/issues/47169

    using var searcher = new DirectorySearcher(rootEntry)
    {
        SearchScope = SearchScope.Subtree,
        Filter = query,
        Sort = new SortOption(criteria.Sort, sortDirection),
        VirtualListView = new DirectoryVirtualListView(0, pageSize - 1, end),
        PageSize = 0
    };
    var searchResults = searcher.FindAll();
    foreach (SearchResult searchResult in searchResults)
    {
        //do something with entity here ...
    }

    //hack to properly get totals
    var virtualListView = searchResults.GetType().GetProperty("VLVResponse", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.GetValue(searchResults) as DirectoryVirtualListView;
    var count = virtualListView?.ApproximateTotal;
    //Instead of simply 
    //var count = searchResults.Count;