作为测试,我会尝试的第一件事是在您创建这样的目录条目时硬编码您想要的路径:
DirectoryEntry de = new DirectoryEntry("LDAP://OU=Users,DC=company,DC=local");
这将很快告诉您这是否是您的 Active Directory 中的实际路径。我不知道您的 AD 是什么样子,所以我无法告诉您这是否是有效路径。在您的 Active Directory 用户和计算机 MMC 插件下,如果此路径正确,那么您应该有您的根域,并且根目录下有一个名为 Users 的 OU 文件夹。
路径是在 AD 中向后生成的,因此如果您的用户文件夹位于根目录之外的另一个 OU 下,那么它将是
DirectoryEntry de = new DirectoryEntry("LDAP://OU=Users,OU=<first OU folder>,DC=company,DC=local");
所以您的 AD 架构如下所示:
Root
|
--><first OU folder>
|
-->Users
一篇关于如何在 .NET 中管理 Active Directory 的精彩文章:
HowTo: Do (Almost) Everything in Active Directory via C#
您可能还想研究 .Net 3.5 框架中提供的 System.DirectoryServices、System.DirectoryServices.ActiveDirectory 和 System.DirectoryServices.AccountManagement 命名空间。我相信 System.DirectoryServices 和 ActiveDirctory 命名空间在 .Net 1.1 中可用,AccountManagement 是在 .Net 3.5 中引入的。
Microsoft Documentation - A lot of good links on how to use the namespace
附录:
要真正在 AD 中找到用户,您需要执行以下操作:
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://DC=company,DC=local";
de.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user) (cn=" + username + "))";
SearchResult result = deSearch.FindOne();
if (result != null)
{
DirectoryEntry deUser = new DirectoryEntry(result.Path);
... do what ever you need to the deUser
deUser.Close();
}