【发布时间】:2010-07-28 17:27:14
【问题描述】:
我正在尝试使用 LDAP (DirectorySearcher class) 列出位于域内某个组织单位中的所有用户。
我要连接的域不是当前域,并且我要查看的 OU 位于非常深的路径中,其中一些 OU 名称在其他地方重复,例如:
MyDomain.LOCAL/MyCompany/Clients/Contoso/Financial Site/Financial Services/Users
我可以使用以下代码列出域内的所有用户:
// Build the directory entry
var directoryEntry = new DirectoryEntry(_ldapServer, _domain + "\\" +
_systemUser, _systemPassword);
try
{
// Bind to the native AdsObject to force authentication of the system user.
// It will throw an exception if this is an invalid account
object obj = directoryEntry.NativeObject;
}
catch (Exception ex)
{
throw new Exception("Error authenticating system user. " + ex.Message, ex);
}
// create a directory searcher for that OU
DirectorySearcher users = new DirectorySearcher(directoryEntry);
// set the filter to get just the users
users.Filter = "(&(objectClass=user)(objectCategory=Person))";
// add the attributes you want to grab from the search
users.PropertiesToLoad.Add("givenName");
users.PropertiesToLoad.Add("sn");
users.PropertiesToLoad.Add("mail");
users.PropertiesToLoad.Add("name");
// grab the users and do whatever you need to do with them
var allFound = users.FindAll();
foreach (SearchResult oResult in allFound)
{
// etc
}
这很有效,并获取了位于根(域)中的所有用户的巨大列表。
但是,我希望获取特定 OU 下的用户。
我尝试了以下行:
var directoryEntry = new DirectoryEntry(_ldapServer +
"/ou=MyCompany/Clients/Contoso/Financial Site/Financial Services/Users",
_domain + "\\" + _systemUser, _systemPassword);
我得到了错误:
验证系统用户时出错。发生操作错误。
有谁知道我如何在DirectorySearcher 中更具体地说明我感兴趣的 OU?
已解决!
最终的路径字符串(以我为例)应如下所示(不含换行符):
LDAP://DomainControllerServer/OU=Users,OU=金融服务,
OU=Financial Site,OU=Contoso,OU=Clients,OU=MyCompany,
DC=MyDomain,DC=LOCAL
DomainControllerServer = 在我的例子中的 IP 地址。
-- FQDN: MyDomain.LOCAL - 以句点分隔的 DC={part} 列表
|-- OU: 我的公司
|-- OU: 客户
|-- OU:Contoso
|-- OU:金融网站
|-- OU:金融服务
|-- OU:用户
请记住使用反斜杠 (\) 转义无效字符,例如:+ , \ = /。
这是一场噩梦,但幸运的是它现在有效。
【问题讨论】:
-
我使用stackoverflow.com/questions/1050043/… 作为一次浏览 OU 1 级别的起点,希望我能完成这项工作。
标签: c# active-directory ldap