C#使用DirectoryVirtualListView来分页ldap查询结果

时间:2019-06-11 04:48:07

标签: c# ldap directoryservices

我正在尝试从LDAP服务器获取用户。该服务器每个响应限于200个结果,我想让所有超过5000个用户。所以我需要做一些分页。到目前为止,我已经尝试了两种方法:

  1. 设置DirectorySearcher PageSize属性。这种方法引发了一个异常,指出“ [DSA]:需要链接(DSP)时无法进行挂接”。这是代码
DirectoryEntry rootEntry = new DirectoryEntry("LDAP://server.name");
rootEntry.Username = "cn=any,o=any,dc=any,dc=any";
rootEntry.Password = "thepassword";
rootEntry.AuthenticationType = AuthenticationTypes.FastBind; 
using (DirectorySearcher searcher = new DirectorySearcher(rootEntry))
{
    searcher.PageSize = 50;
    searcher.Filter = "(&(objectClass=person))";
    foreach (SearchResult sr in searcher.FindAll())
    {
        Console.WriteLine(sr.Path);
    }
}
  1. 使用VirtualListView。这还会引发异常“无法设置VirtualListView属性值”,并且代码:
DirectoryEntry rootEntry = new DirectoryEntry("LDAP://server.name", "cn=any,o=any,dc=any,dc=any", "any", AuthenticationTypes.FastBind);
using (DirectorySearcher searcher = new DirectorySearcher(rootEntry))
{
    searcher.Filter = "(&(objectClass=person))";
    searcher.Sort = new SortOption("cn", SortDirection.Ascending);
    searcher.VirtualListView = new DirectoryVirtualListView(25);

    foreach (SearchResult sr in searcher.FindAll())
    {
        Console.WriteLine(sr.Path);
    }
}

谁能告诉我我在做什么错?预先感谢。

1 个答案:

答案 0 :(得分:1)

using (var directoryEntry = new DirectoryEntry(@"LDAP://TestDomain")
{
    Username = @"TestDomain\TestUser",
    Password = "T@st#1"
})
{
    var directorySearcher = new DirectorySearcher(directoryEntry)
    {
        VirtualListView = new DirectoryVirtualListView(0, 9, 1)
    };

    // will give you only users with mail
    var filter = "(&(objectCategory=person)(objectClass=user)(mail=*))";

    directorySearcher.Filter = filter;
    directorySearcher.Sort = new SortOption() { PropertyName = "displayname", 
                                                 Direction = SortDirection.Ascending };

    directorySearcher.PropertiesToLoad.Add("displayname");
    directorySearcher.PropertiesToLoad.Add("mail");
    directorySearcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
    directorySearcher.SizeLimit = 100;

    var results = directorySearcher.FindAll();
    var names = new List<string>();

    foreach (SearchResult r in results)
    {
        // Map the result 
    }
}

您必须使用它,并且默认情况下会按cn对用户进行排序

1. VirtualListView = new DirectoryVirtualListView(0, 9, 1)
2. VirtualListView = new DirectoryVirtualListView(0, 49, 100);
  1. 从0到9会给您10条记录
  2. 将从100个用户中吸引50个用户。