2011-05-01 66 views
2

如何从活动目录获取用户经理电子邮件ID?我已经编写了代码,可以根据用户名获得用户的名字,姓氏,电子邮件ID和他的经理姓名,但是我想要获得经理电子邮件ID和他的经理姓名。从活动目录获取经理电子邮件ID

请问有人能帮助我如何得到这个?这里是我的代码:

protected void ddlAdsuser_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE"); 
    string myDomain = root.Properties["defaultNamingContext"].Value.ToString(); 
    DirectoryEntry domain = new DirectoryEntry("LDAP://" + myDomain); 
    DirectorySearcher dsUsers = new DirectorySearcher(domain); 
    dsUsers.Filter = "(userPrincipalName=" + ddlAdsuser.Text + ")"; 
    foreach (SearchResult sResultSet in dsUsers.FindAll()) 
     { 
      lblfname.Text = GetProperty(sResultSet, "givenName"); 
      lbllname.Text = GetProperty(sResultSet, "sn"); 
      lblemail.Text = GetProperty(sResultSet, "mail"); 

      string Manager = string.Empty; 
      Manager = GetProperty(sResultSet, "manager"); 
      if (Manager != "") 
      { 
       if (Manager.Contains("CN=")) 
       { 
        int Length = Manager.IndexOf(','); 
        Manager = Manager.Substring(3, Length - 3); 
       } 
       else 
       { 
        Manager = string.Empty; 
       } 
      }    
      lblManagerID.Text = Manager; //Here displaying the manager name. 
     }  
} 

public static string GetProperty(SearchResult searchResult, string PropertyName) 
{ 
    if (searchResult.Properties.Contains(PropertyName)) 
    { 
     return searchResult.Properties[PropertyName][0].ToString(); 
    } 
    else 
    { 
     return string.Empty; 
    } 
} 

回答

0

只需要第二次搜索经理。

请注意,您构建查询过滤器的方法是越野车,您需要转义某些字符(特别是"引用)以避免根据用户输入而导致查询被破坏。

+0

Lucero->我没有得到你能不能详细说明。 – sumit 2011-05-01 16:33:30

+0

什么部分?用你建立过滤器的方式寻找问题的管理者? – Lucero 2011-05-01 16:55:51

+0

寻找问题的管理者。 – sumit 2011-05-01 17:21:41

1

简单的代码和巨大的工作:

public static string GetEmail(string userId) 
    { 
     PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 
     UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userId); 
     return user.EmailAddress; 
    } 

您必须添加组件System.DirectoryServices.AccountManagement.dll。 如果您在连接到AD时遇到任何问题,您可以尝试在PrincipalContext构造函数中添加AD服务器名称。

4
DirectorySearcher objDirSearch = new DirectorySearcher(SearchRoot); 
DirectoryEntry dentUser = null; 
string pstrFieldName, pstrValue; 

pstrFieldName = "company"; 
pstrValue = "12345"; //Employee number 

/*setting the filter as per the employee number*/ 
objDirSearch.Filter = "(&(objectClass=user)(" + pstrFieldName + "=" + pstrValue + "))"; 

SearchResult objResults = objDirectorySearch.FindOne(); 

dentUser = new DirectoryEntry(objResults.Path);} 

string strManager = dentUser.Properties["manager"].Value.ToString(); 

PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, strManager); 

string strManagerMailID = user.EmailAddress;