我建议使用较低级别的DirectoryServices.Protocols
命名空间而不是DirectoryServices.AccountManagement
这样的东西。
我(与许多其他人一起)使用这些AccountManagement
库时遇到的问题是缺乏自定义和配置。话虽这么说,这也是我搜索 Active Directory 的方式,System.DirectoryServices.Protocols.SearchScope
也是如此。
//Define the connection
var ldapidentifier = new LdapDirectoryIdentifier(ServerName, port);
var ldapconn = new LdapConnection(ldapidentifier, credentials);
//Set some session options (important if the server has a self signed cert or is transferring over SSL on Port 636)
ldapconn.SessionOptions.VerifyServerCertificate += delegate { return true; };
ldapconn.SessionOptions.SecureSocketLayer = true;
//Set the auth type, I'm doing this from a config file, you'll probably want either Simple or Negotatie depending on the way your directory is configured.
ldapconn.AuthType = config.LdapAuth.LdapAuthType;
这是DirectoryServices
真正开始发光的地方。您可以轻松定义过滤器以按特定组或子组进行搜索。你可以做这样的事情:
string ldapFilter = "(&(objectCategory=person)(objectclass=user)(memberOf=CN=All Europe,OU=Global,dc=company,dc=com)";
//Create the search request with the domain, filter, and SearchScope. You'll most likely want Subtree here, but you could possibly use Base as well.
var getUserRequest = new SearchRequest(Domain, ldapFilter, SearchScope.Subtree)
//This is crucial in getting the request speed you want.
//Setting the DomainScope will suppress any refferal creation during the search
var SearchControl = new SearchOptionsControl(SearchOption.DomainScope);
getUserRequest.Controls.Add(SearchControl);
//Now, send the request, and get your array of Entry's back
var Response = (SearchResponse)ldapconn.SendRequest(getUserRequest);
SearchResultEntryCollection Users = Response.Entries;
这可能不是您所需要的,但正如您所见,您将有更多的灵活性来更改和修改搜索条件。我使用这段代码来搜索海量的域结构,它几乎是瞬时的,即使有大量的用户和组。