2012-09-27 17 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。這可能比在代碼中嘗試它們容易得多。