2015-05-06 95 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

相关问题