2013-01-11 39 views
4

我想從用戶那裏獲得Active Directory屬性,我想使用System.DirectoryServices.AccountManagement如何通過System.DirectoryServices.AccountManagement命名空間獲取Active Directory用戶屬性?

我的代碼:

public static void GetUserProperties(string dc,string user) 
     { 
      PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc); 
      UserPrincipal u = UserPrincipal.FindByIdentity(ctx, user); 

      string firstname = u.GivenName; 
      string lastname = u.Surname; 
      string email = u.EmailAddress; 
      string telephone = u.VoiceTelephoneNumber; 

      ...//how I can get company and other properties? 
     } 
+0

你是指什麼公司? –

+2

可能dup我不需要使用擴展方法的同樣需要相同的方法http://stackoverflow.com/questions/1785751/how-to-get-company-and-department-from-active-directory-given-a-userprincipa – prthrokz

+0

一個簡單的解決方案。 – Rama

回答

9

可以過渡到的DirectoryServices命名空間來得到你所需要的任何財產。

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc); 
UserPrincipal u = UserPrincipal.FindByIdentity(ctx, user); 

string firstname = u.GivenName; 
string lastname = u.Surname; 
string email = u.EmailAddress; 
string telephone = u.VoiceTelephoneNumber; 
string company = String.Empty; 

...//how I can get company and other properties? 
if (userPrincipal.GetUnderlyingObjectType() == typeof(DirectoryEntry)) 
{ 
    // Transition to directory entry to get other properties 
    using (var entry = (DirectoryEntry)userPrincipal.GetUnderlyingObject()) 
    { 
     if (entry.Properties["company"] != null) 
      company = entry.Properties["company"].Value.ToString(); 
    } 
} 
相關問題