如果目录条目不存在
本文关键字:不存在 如果 | 更新日期: 2023-09-27 18:36:48
在 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;
}
但是,在测试用户是否输入不存在的域时,这工作正常。
例如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
存在
但是目录条目返回一个对象,当我需要测试字符串时,我认为路径是错误的......有什么想法吗?
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;
}
在访问之前不要使用 Exists()
函数进行测试。LDAP 目录是易失性的,可以从您下方更改。这是一个竞争条件。
相反,请使用 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
}
例如,假设域是"example.com"
测试路径应LDAP://example.com
。
如果不提供 DN,它将自动连接到域根对象。所以在上面的例子中,它实际得到的对象是LDAP://example.com/DC=example,DC=com