2012-09-27 22 views
1

我在这里变得疯狂,我非常感谢您的帮助! 简单地说,我想使用DirectoryEntry类从Active Directory获取用户名或任何内容。无法从Directoryentry获取用户

我用userprinciple,它工作得很好,但我需要得到的属性(用户的经理)只在DirectoryEntry中可用。

我的问题是,我看了这么多的在线,我从那里得到的代码,但由于某种原因,它永远不会工作,总是返回空值。这里是一个例子:

public static DirectoryEntry GetUser(string UserName) 
{ 
    //create an instance of the DirectoryEntry 
    DirectoryEntry de = new DirectoryEntry("LDAP://" + "OU=AnotherOU,OU=xx,OU=Testvironments,DC=abc,DC=local"); 

    //create instance fo the direcory searcher 
    DirectorySearcher deSearch = new DirectorySearcher(de); 

    deSearch.SearchRoot = de; 
    //set the search filter 
    deSearch.Filter = "(&(objectCategory=user)(cn=" + UserName + "))"; 
    //deSearch.SearchScope = SearchScope.Subtree; 

    //find the first instance 
    SearchResult results = deSearch.FindOne(); 

    //if found then return, otherwise return Null 
    if (results != null) 
    { 
     //de= new DirectoryEntry(results.Path,ADAdminUser,ADAdminPassword,AuthenticationTypes.Secure); 
     //if so then return the DirectoryEntry object 
     return results.GetDirectoryEntry(); 
    } 
    else 
    { 
     return null; 
    } 
} 

我不知道为什么这段代码返回null。

在此先感谢。

回答

2

你可以尝试这样的

//create instance for directory entry 
DirectoryEntry de = new DirectoryEntry("LDAP://" + "OU=AnotherOU,OU=xx,OU=Testvironments,DC=abc,DC=local"); 

//create instance fo the directory searcher 
DirectorySearcher deSearch = new DirectorySearcher(de);; 

//set the search filter 
deSearch.Filter = "(&(objectClass=user)(|(SAMAccountName=" + UserName+ ")(givenName=" + UserName+ ")(name=" + UserName+ ")(SN=" + UserName+ "))"; 

//find the first instance 
SearchResult results = deSearch.FindOne(); 

//if found then return, otherwise return Null 
if (results != null) 
{ 
    //The desired property you want , you can extract in this way. 
    DomainName = results .Properties["SamAccountName"][0].ToString(); 
    return domainName 
} 
else 
{ 
    return null; 
} 

希望这是你在找什么。

+0

这里的域名是用户ID,用户试图登录到机器。它是一个独特的ID。我很抱歉,应该在这里使用了其他的东西... – RL89

0

你想要cn,samAccountname,displayNameuserPrincipalName属性吗? samAccountName是传统(NT 4.0)风格的用户名,displayName通常是名和姓,userPrincipalName的格式与电子邮件地址([email protected])类似。

无论哪种方式,如果您想测试不同的查询,请使用交互式LDAP查询工具,如ldp.exe。这可能比在代码中尝试它们容易得多。