如果directoryEntry不存在

时间:2015-01-07 16:59:34

标签: c# exists directoryentry

在asp.net c#中使用目录条目,如果我打电话:

ADUtils newAdClass = new ADUtils("dl-dom", "ad.test", "Password?1");
    List<string> domUsers = newAdClass.GetDomainUsers();
----------------------------------------------------------------------------------
-------------------------------------------------------------------------------

public List<string> GetDomainUsers()
{
    //returned list
    List<string> domainUsers = new List<string>();

    //create connection
    DirectoryEntry entry = new DirectoryEntry(_lDAPPath, _ldapUser, _ldapPassword);
    DirectorySearcher search = new DirectorySearcher(entry);

    //search subtree nodes
    search.SearchScope = SearchScope.Subtree;

    //Active Directory LDAP: All email users (alternate)
    search.Filter = "(&(objectClass=user)(objectcategory=person))";

    //create results objects from search object 
    SearchResultCollection results = search.FindAll();

    //run through list, for each entry remove 'CN=' and add 'user' to list
    for (int i = 0; i < results.Count; i++)
    {
        DirectoryEntry de = results[i].GetDirectoryEntry();
        string user = de.Name.Replace("CN=", "");
        domainUsers.Add(user);
    }
    return domainUsers;
}

但是在测试用户是否输入不存在的域时,这样可以正常工作。 e.g。

ADUtils newAdClass = new ADUtils("FAKE-dl-dom", "ad.test", "Password?1");

这会在我的代码中引发错误,所以我试图使用http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.exists%28v=vs.110%29.aspx 存在

但DirectoryEntry条目返回一个对象,因为我需要测试字符串,我认为路径是错误的...任何想法?

string entry1 = _lDAPPath + "," + _ldapUser + "," + _ldapPassword;
//entry1 returns: LDAP://DC=dl-dom,ad.test,Password?1

if (DirectoryEntry.Exists(entry1))
{
    DirectorySearcher search = new DirectorySearcher(entry);

当我使用上面的代码时,我得到了异常

An invalid dn syntax has been specified.

构造

public ADUtils(string LDAPDomain, string ADUser, string ADUserPwd)
{
    _lDAPPath = "LDAP://DC=" + LDAPDomain;
    _ldapUser = ADUser;
    _ldapPassword = ADUserPwd;
}

2 个答案:

答案 0 :(得分:0)

例如,假设域名为&#34; example.com&#34;
测试路径应为LDAP://example.com

如果您不提供DN,它将自动连接到域根对象。所以在上面的例子中,它实际得到的对象是LDAP://example.com/DC=example,DC=com

答案 1 :(得分:0)

访问前请勿使用Exists()功能进行测试。 LDAP目录是 volatile ,可以从您的下方更改。这是竞争条件

相反,使用try / catch块,并在失败时处理异常:

try
{
    //create results objects from search object 
    SearchResultCollection results = search.FindAll();

    //run through list, for each entry remove 'CN=' and add 'user' to list
    for (int i = 0; i < results.Count; i++)
    {
        DirectoryEntry de = results[i].GetDirectoryEntry();
        string user = de.Name.Replace("CN=", "");
        domainUsers.Add(user);
    }
}
catch(Excpetion e)
{
    //add code here to process the error

    //after debugging, you may even decide to just swallow the exception 
    // and return an empty collection
}