c# - 为什么无法通过 PrincipalContext 联系 Active Directory 服务器?

标签 c# active-directory

我在从我的 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/

相关文章:

python - 如何使用 django-python3-ldap 从 Active Directory 组在 Django 模型中创建组和权限?

c# - 获取路径的最后一个字段?

azure - 在 Azure Active Directory (WAAD) 中设置直接报告

powershell - Get-ADGroup 中的格式成员属性

javascript - 在不根据 Django 管理站点检查用户的情况下登录 Django 网站

powershell - 从数组中选择选项

c# - 用于检查 url 和共享文件路径的正则表达式

c# - 将 Guid 传递给存储过程会引发 Microsoft.Data.SqlClient.SqlException : 'Incorrect syntax near ' @Id'. '

c# - 每次调用时更改行为的最小起订量语法是什么?

c# - 使用 Code First Entity Framework 的数据访问层、模型层和 POCO 类