2013-04-03 126 views
0

這是我想使用的代碼,但我沒有真正與它成氣候:如何從Exchange電子郵件地址獲取Active Directory用戶名?

public static string GetUserIdFromEmail(string emailAddress) 
    { 
     string displayName = string.Empty; 

     if (emailAddress.Contains("@sub.domain.edu") || emailAddress.Contains("@domain.edu")) 
     { 
      displayName = emailAddress.Split(new char[] { '@' })[0]; 
     } 
     else 
     { 
      //no active directory account. 
      return string.Empty; 
     } 


     // set up domain context 
     using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) 
     { 
      // find user by display name 
      try 
      { 
       UserPrincipal user = UserPrincipal.FindByIdentity(ctx, displayName); 
       if (user != null) 
       { 
        return user.SamAccountName; // or UserPrincipleName 
       } 
       else 
       { 
        return string.Empty; 
       } 
      } 
      catch (Exception) 
      { 
       return "Error"; 
      } 
     } 
    } 

這是我知道的就我們目前的系統的東西:

  1. 電子郵件打算是唯一的,遵循一定的命名約定

  2. 命名約定是名字的第一個字母和整個姓氏(dstanley)。

  3. 在Exchange一些老的賬戶[email protected]

  4. 我不知道我在做什麼,但我知道我想要什麼。

我希望能夠獲取用戶域電子郵件地址並在活動目錄中查找其記錄。上面的代碼是正確的,還是有一些我可以做的更簡單的事情?

+0

就個人而言,我喜歡錄取數字4的膽量。 – MyCodeSucks 2013-04-03 20:14:04

+0

哈,膽量?更像是'請不要向我扔石頭,如果這是一個愚蠢的問題'種說法。我從來沒有真正與Intranet應用程序合作過,並嘗試以編程方式獲取AD內容。 – ledgeJumper 2013-04-03 20:15:38

+1

在我們的職業中,經常會有人因爲沒有意識到完全可以承認自己不知道自己在做什麼。這是這個網站存在的原因之一。 – MyCodeSucks 2013-04-03 20:17:42

回答

0

要使用標準活動目錄庫訪問用戶電子郵件,您必須先擁有samaccount。這意味着對這個問題的解決方案要求您迭代每個samaccount並比較電子郵件地址,直到找到匹配項。

僞碼

foreach(user in activedirectory) 
{ 
    if (user.email = targeted_email) 
    { 
     return matched samaccount 
    } 
} 

我不相信有一個更好的方式來處理這一點,因此它是一個資源密集型解決方案。

相關問題