我在从我的 WinForm 应用程序访问 Active Directory 时遇到了一些问题。我想要的是从 Active Directory 创建用户和查询用户。
这是查找用户的代码片段:
public bool FindUser(string username)
{
using (PrincipalContext context = new PrincipalContext(
ContextType.Domain,
this.domainName,
this.DomainUserName,
this.DomainPassword))
{
UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
return (user != null) ? true : false;
}
}
我无法根据给定的参数创建 PrincipalContext
的对象。我收到此异常:
Exception: The server could not be contacted.
内部异常说明,
Inner Exception: The LDAP server is unavailable.
域运行的位置。我可以 ping 通它,也可以连接到这个域。
最佳答案
您可以尝试下一个代码。
public bool FindUser2(string userName)
{
try
{
DirectoryContext context = new DirectoryContext(
DirectoryContextType.Domain,
domainName,
domainName + @"\" + domainUserName,
domainPassword);
DirectoryEntry domainEntry = Domain.GetDomain(context).GetDirectoryEntry();
DirectorySearcher searcher = new DirectorySearcher(domainEntry,
"(|(objectCategory=user)(cn=" + domainUserName + "))");
SearchResult searchResult = searcher.FindOne();
return searchResult != null;
}
catch
{
return false;
}
}
关于c# - 为什么无法通过 PrincipalContext 联系 Active Directory 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1747856/