2009-12-27 126 views
1

我想檢查一個OU中是否存在選定的用戶(通過他/她登錄的用戶名),完成此操作的最重要的方法是什麼? 之後,我想選擇用戶並更改他/她的密碼。檢查用戶是否存在於ou

我發現了一些幫助在這裏:http://www.codeproject.com/KB/system/everythingInAD.aspx#46

但我發現的代碼是這樣的:

 
public static bool Exists(string objectPath) 
{ 
    bool found = false; 
    if (DirectoryEntry.Exists("LDAP://" + objectPath)) 
    { 
     found = true; 
    } 
    return found; 
} 

至極可以summeried爲:

 
return DirectoryEntry.Exists("LDAP://" + objectPath); 

所以,我真的不如果我擁有的是一個用戶名和OU名稱以及一個域名,我知道該信任誰,以及我應該傳遞給objectPath的信息。

請幫忙。

謝謝。

回答

4

由於用戶名在域內必須是唯一的,我不認爲我會過分關心OU。構建此代碼可能會使代碼更加脆弱,並且會使代碼更加複雜。如果可以,我會嘗試使用新的UserPrincipal類。

using (var context = new PrincipalContext(ContextType.Domain)) 
{ 
    using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName)) 
    { 
     if (user != null) 
     { 
      user.ChangePassword(oldPassword, newPassword); 
      // or if you don't have the user's old password and 
      // do have enough privileges. 
      // user.SetPassword(newPassword);   
     } 
    } 
} 
+0

請問您能解釋爲什麼我應該使用關鍵字Using? – 2009-12-27 14:10:49

+1

PrincipalContext和UserPrincipal都實現了IDisposable。通過將它們包裝在using語句中,確保在完成對象時調用Dispose並釋放對象使用的非託管資源。 – tvanfosson 2009-12-27 16:01:19