如何在WPF中检查Active Directory中的用户名



我想检查Active Directory中是否存在用户名?根据这一点,我需要执行代码。

我有域名和用户名。如何使用DirectorySearcher检查Active Directory中是否存在没有密码的用户名。

您的进程必须在active directory用户下运行,否则在创建PrincipalContext时还应提供active directory用户凭据。这是通过用户名查找用户的简单代码:

  var context = new PrincipalContext(ContextType.Domain, "yourDomainHost");
  var userInfo = UserPrincipal.FindByIdentity(context, userName);

编辑:

如果你需要使用目录搜索器,你可以尝试这种方法:

     bool ContainsUser(string domain, string userName)
    {
        string ldapBase = string.Format("LDAP://{0}", domain);
        // in case if process is not running under AD user use: new DirectoryEntry(ldapBase, "userName", "password")
        using (var entry = new DirectoryEntry(ldapBase)) 
        {
            using (var searcher = new DirectorySearcher(entry))
            {
                searcher.Filter = string.Format("(sAMAccountName={0})", userName);
                return searcher.FindOne() != null;
            }
        }
    }

您可以尝试这种方法:

DirectoryEntry entry = new DirectoryEntry("LDAP://DomainName");
DirectorySearcher dsearcher = new DirectorySearcher(entry);
dsearcher.Filter = "samaccountname=" + username;
SearchResult result = dsearcher.FindOne();
if(null!=result) //User Exists
{
  //Do your stuff here
}
else //User Not Exists
{
  //Do your stuff here
}

上面的代码假定您的AD服务器允许匿名访问。

最新更新