DC 是您的域。如果您想连接到域 example.com,则您的 dc 为:DC=example,DC=com
实际上,您不需要域控制器的任何主机名或 IP 地址(可能有很多)。
想象一下您正在连接到域本身。因此,要连接到域 example.com,您可以简单地编写
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
你就完成了。
您还可以指定用于连接的用户和密码:
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");
另请确保始终以大写形式书写 LDAP。我遇到了一些麻烦和奇怪的异常,直到我在某处读到我应该尝试用大写写它,这解决了我的问题。
The directoryEntry.Path
财产可以让您更深入地了解您的领域。因此,如果您想搜索特定 OU(组织单位)中的用户,您可以在那里进行设置。
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";
这将匹配以下 AD 层次结构:
只需从最深到最高写出层次结构即可。
现在你可以做很多事情 http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C
例如,按帐户名搜索用户并获取用户的姓氏:
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
PageSize = int.MaxValue,
Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};
searcher.PropertiesToLoad.Add("sn");
var result = searcher.FindOne();
if (result == null) {
return; // Or whatever you need to do in this case
}
string surname;
if (result.Properties.Contains("sn")) {
surname = result.Properties["sn"][0].ToString();
}