2011-05-01 70 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;