2015-05-06 92 views
1

如何獲取與用戶關聯的活動目錄管理器中的經理姓名和電子郵件地址等詳細信息?從Active Directory獲取用戶管理器詳細信息

我能夠得到用戶的所有細節:

ActiveDirectory.SearchUserinAD("ads", "sgupt257"); 

public static bool SearchUserinAD(string domain, string username) 
     { 
      using (var domainContext = new PrincipalContext(ContextType.Domain, domain)) 
      { 
       using (var user = new UserPrincipal(domainContext)) 
       { 
        user.SamAccountName = username; 
        using (var pS = new PrincipalSearcher()) 
        { 
         pS.QueryFilter = user; 
         var results = pS.FindAll().Cast<UserPrincipal>(); 
         { 
          foreach (var item in results) 
          {         
           File.WriteAllText("F:\\webapps\\CIS\\UserInfo.txt", item.DisplayName + item.Name + item.EmailAddress + item.EmployeeId + item.VoiceTelephoneNumber + item.Guid + item.Context.UserName + item.Sid); 
          } 
          if (results != null && results.Count() > 0) 
          { 
           return true; 
          } 
         } 
        } 
       } 
      } 
      return false; 
     } 

感謝。

+0

AD經理?這是什麼 ? – MajkeloDev

+0

AD經理與用戶關聯... – user662285

+0

從來沒有聽說過它。這是奇怪的,因爲我與AD工作了約2年 – MajkeloDev

回答

2

我使用DirectorySearcher從AD獲取數據。 你可以得到經理類似的東西:

DirectoryEntry dirEntry = new DirectoryEntry("LDAP://DC=company,DC=com"); 
DirectorySearcher search = new DirectorySearcher(dirEntry); 
search.PropertiesToLoad.Add("cn"); 
search.PropertiesToLoad.Add("displayName"); 
search.PropertiesToLoad.Add("manager"); 
search.PropertiesToLoad.Add("mail"); 
search.PropertiesToLoad.Add("sAMAccountName"); 
if (username.IndexOf('@') > -1) 
{ 
    // userprincipal username 
    search.Filter = "(userPrincipalName=" + username + ")"; 
} 
else 
{ 
    // samaccountname username 
    String samaccount = username; 
    if (username.IndexOf(@"\") > -1) 
    { 
     samaccount = username.Substring(username.IndexOf(@"\") + 1); 
    } 
    search.Filter = "(sAMAccountName=" + samaccount + ")"; 
} 
SearchResult result = search.FindOne(); 
result.Properties["manager"][0]; 

現在你知道誰是經理,這樣你就可以查詢有關管理器數據。

3

如果您想使用Principals而不是DirectorySearcher,您可以在UserPrincipal對象上調用GetUnderlyingObject()並獲取DirectoryEntry。

using(var user = new UserPrincipal(domainContext)) 
{ 
    DirectoryEntry dEntry = (DirectoryEntry)user.GetUnderlyingObject(); 
    Object manager = dEntry.Properties["manager"][0]; 
} 
+0

當使用這種方法時,我得到一個錯誤,指出'在調用此方法之前必須持久化主體對象。當獲取底層對象時。有任何想法嗎? – DaRoGa

+0

@DaRoGa我相信你可能已經找到了答案,但一定要在初始化你的'PrincipalContext'類時指定你的域名。我還使用了'UserPrincipal.FindByIdentity(context,IdentityType.SamAccountName,username)'而不是'new UserPrincipal(domainContext)'。這對我來說很有效,因爲在玩過上面的代碼後,我收到了一個不同的錯誤。 – GibralterTop

相關問題