2011-12-21 148 views
1

我需要从活动目录访问信息。我使用的代码Active Directory访问

DirectoryEntry entry = new DirectoryEntry("LDAP://domain", "AD_id", "password"); 

DirectorySearcher search = new DirectorySearcher(entry); 
try 
{ 
    search.Filter = "(SAMAccountName=AD_id)"; 
    search.PropertiesToLoad.Add("cn"); 
    search.PropertiesToLoad.Add("sn"); 
    search.PropertiesToLoad.Add("givenName"); 
    search.PropertiesToLoad.Add("email"); 

    SearchResult result = search.FindOne(); 

    if (result != null) 
     lbl_result.Text = result.Path.ToString(); 
    else 
     lbl_result.Text = "failier"; 
} 
catch (Exception ex) 
{ 
    lbl_result.Text = ex.Message; 
} 

我顺利拿到在给定的格式

LDAP://domain/CN=username,OU=aaa,OU=bbb,OU=ccc,DC=domain,DC=com 

有关用户的一些信息,但是,这不是我所需要的全部信息,例如电子邮件地址未在上述(aaa,bbb和ccc是其他一些信息) 如果我在做错某些事情,请帮助我。 我是这种编程的新手。 我会很感激。

回答

0

如果您使用.NET 3.5或更高版本,则应检查System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读全部内容:

基本上,你可以定义域范围内,并可以轻松地查找用户和/或组AD:

// set up domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// find a user 
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName"); 

if(user != null) 
{ 
    // do something here....  
    string emailAddress = user.EmailAddress; 
} 

UserPrincipal类包含许多可读出的属性(并为其设置新值)。

新的S.DS.AM可以很容易地与AD中的用户和群组玩耍!

当然 - 你也可以搜索用户!

您可以使用PrincipalSearcher和“查询通过例如”主要做你的搜索:

// create your domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the SAMAccountName of "ad_id" 
UserPrincipal qbeUser = new UserPrincipal(ctx); 
qbeUser.SamAccountName = "ad_id"; 

// create your principal searcher passing in the QBE principal  
PrincipalSearcher srch = new PrincipalSearcher(qbeUser); 

// find all matches 
foreach(var found in srch.FindAll()) 
{ 
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....   
    UserPrincipal foundUser = found as UserPrincipal; 

    if(foundUser != null) 
    { 
     // do something here....  
     string emailAddress = foundUser.EmailAddress; 
    } 
} 
+0

我非常感谢您的回复。我正在尝试... – Lali 2011-12-21 10:21:03

+0

亲爱的marc_s,PrincipalContext构造函数给出错误“服务器无法联系。”所以我提到了新的PrincipalContext(ContextType.Domain,“domainname”)。但接下来当我将SamAccountName设置为AD_id时,它显示错误“登录失败:未知用户名或错误密码”。我设置了新的UserPrincipal(ctx,“AD_id”,“Pwd”,true),但错误是一样的... – Lali 2011-12-21 11:07:44

+0

@liaqatali:研究[PrincipalContext上的MSDN文档](http://msdn.microsoft.com/ en-us/library/system.directoryservices.accountmanagement.principalcontext.aspx) - 它有几个重载的构造函数,您可以在其中定义用于绑定到AD的凭据 – 2011-12-21 13:21:19