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

问题描述:

我想检查Active Directory中是否存在用户名? 并取决于我需要执行的代码。如何检查WPF中Active Directory中的用户名

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

+1

K T - 为什么你只接受4个答案给你16个问题?为什么你会忽略任何评论? – MikroDel

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

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; 
      } 
     } 
    } 
+0

如何使用DirectorySearcher查找? –

你可以试试这个方法:

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服务器允许匿名访问。