使用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的情况
但是DirectoryEntry entry返回一个对象,当我需要测试字符串时,我想路径是wrong...any ideas?
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;
}发布于 2015-01-08 11:51:50
例如,假设域名为"example.com“
测试路径应为LDAP://example.com。
如果不提供DN,它将自动连接到域根对象。因此,在上面的示例中,它实际获得的对象是LDAP://example.com/DC=example,DC=com
发布于 2015-01-08 12:14:02
在访问之前,不要使用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
}https://stackoverflow.com/questions/27824575
复制相似问题