[英]Get total number of search results for paginated DirectorySearcher
I am using a DirectorySearch<\/code> to search for objects in an Active Directory.
我正在使用
DirectorySearch<\/code>在 Active Directory 中搜索对象。
I set the
VirtualListView<\/code> property to return just a few values:
我将
VirtualListView<\/code>属性设置为只返回几个值:
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);
}
}
}
There is an ApproximateTotal
property inside DirectoryVirtualListView
class. DirectoryVirtualListView
类内部有一个ApproximateTotal
属性。 You can use it, but remember you should access it after the foreach
block in your code. 您可以使用它,但是请记住您应该在代码中的foreach
块之后访问它。 Just change this line: 只需更改此行:
Console.WriteLine("Found: " + results.Count);
to this one: 对此:
Console.WriteLine("Found: " + searcher.VirtualListView.ApproximateTotal);
All done! 全部做完!
I've ran into a situation where VirtualListView.ApproximateTotal returns zero.我遇到了 VirtualListView.ApproximateTotal 返回零的情况。 I've only encountered this running in netcoreapp3.1 however.但是,我只在 netcoreapp3.1 中遇到过这种情况。
In the event you do get zero records returned, I discovered a hack to retrieve the value如果您确实返回零记录,我发现了一个黑客来检索值
Credit https:\/\/github.com\/dotnet\/runtime\/issues\/47169<\/a>信用https:\/\/github.com\/dotnet\/runtime\/issues\/47169<\/a>
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.