在c#中获得一个活动目录用户
本文关键字:一个 活动 用户 | 更新日期: 2023-09-27 18:10:34
在创建用户之前,我试图检查该用户是否存在于Active Directory中。我使用下面的代码:
private static DirectoryEntry FindActiveDirectoryUser(string userName, string domainName)
{
using (DirectoryEntry domain = new DirectoryEntry("LDAP://" + domainName))
{
using (DirectorySearcher searcher = new DirectorySearcher(domain))
{
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.Filter = "(sAMAAccountName=" + userName + ")";
return searcher.FindOne().GetDirectoryEntry();
}
}
}
我得到错误
A referral was returned from the server.
对于变量userName和domainName,我尝试了FQDN和2000年以前的用户名(例如DOMAIN'User),以及简单的域和用户名。
有人知道如何解决这个问题吗?
试试这个。它会工作的
public GetUserByLoginName(String userName)
{
try
{
using (HostingEnvironment.Impersonate())
{
// This code runs as the application pool user
_directoryEntry = null;
string path = "LDAP://xxx.local/DC=xxx,DC=xxx"; //your LDAP Address
DirectorySearcher directorySearch = new DirectorySearcher(path);
directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))";
SearchResult results = directorySearch.FindOne();
}
}
catch (Exception ex)
{
return null;
}
}