2

我目前在这里有几种方法:

public ADHelper()
        {

           connection =  InitializeConnection();

        }

        private DirectoryEntry InitializeConnection()
        {
            DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://servername.domain.com:389/DC=domain,DC=com");
            ldapConnection.Username = "user"
            ldapConnection.Password = "password";

            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            return ldapConnection;

        }

我想创建另一种方法来检查该域中是否存在对象。我目前正在执行以下操作:

public bool Exists(string objectPath)
        {
            bool found = DirectoryEntry.Exists("LDAP://" + objectPath);
            return found;
        }

但这迫使我指定整个 LDAP 字符串。我想在 Exists() 方法中简单地使用 OU 和 CN 参数扩展初始 ldapConnection 。有没有办法在不公开 Initialize() 方法的情况下实现这一点?

非常感谢!

4

1 回答 1

0

也许是这样的:

public bool AccountExists(string userEmail)
{
    using (var root = GetLdapRoot())
    {
        using (var searcher = new DirectorySearcher(root))
        {
            searcher.Filter = string.Format("(&(objectClass=User)(mail={0}))", userEmail);
            searcher.PropertiesToLoad.Add("email");
            var result = searcher.FindAll();
            return result.Count > 0;
        }
    }
}


private static DirectoryEntry GetLdapRoot()
{
    return new DirectoryEntry("LDAP://DC=com"); //or whatever your root domain is. Set credentials if you need to
}

通过设置过滤器并具体说明要加载的属性,搜索将更加有效。通过使用根目录作为 LDAP:// 字符串,您应该搜索整个目录。

于 2012-09-04T21:53:48.550 回答