2011-08-09 178 views
3

我想設置屬性以解鎖AD中的用戶帳戶,並且使用以下代碼;問題是de不包含userAccountControl並且代碼失敗。解鎖用戶帳戶

我可以通過使用DirectorySearcher得到userAccountControl的值,但這並不幫助我使用de來設置屬性。任何人都可以幫我嗎?在此先感謝

String m_Path = "LDAP://" + distinguishedName; 

using (DirectoryEntry de = new DirectoryEntry(m_Path)) 
{ 
    if (de.Contains("userAccountControl") 
    { 
     int m_Val = (int)de.Properties["userAccountControl"][0].Value; 
     de.Properties["userAccountControl"].Value = m_Val | 0x0001 
     de.CommitChanges; 
    } 
} 

回答

5

我想你需要檢查de.Properties是否含有userAccountControl值!

string ldapPath = "LDAP://" + distinguishedName; 

using(DirectoryEntry de = new DirectoryEntry(ldapPath)) 
{ 
    // check to see if we have "userAccountControl" in the **properties** of de 
    if(de.Properties.Contains("userAccountControl") 
    { 
     int m_Val = (int)de.Properties["userAccountControl"][0].Value ; 
     de.Properties["userAccountControl"].Value = m_Val | 0x0001; 

     de.CommitChanges(); 
    } 
} 

另外,如果你在.NET 3.5及以上,你應該看看System.DirectoryServices.AccountManagement(S.DS.AM)命名空間。在這裏閱讀全部內容:

基本上,你可以定義域範圍內輕鬆地找到和操作的用戶和/或組AD:

// set up domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// find a user 
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName"); 

if(user != null) 
{ 
    // unlock user 
    user.UnlockAccount(); 
} 

新的S.DS.AM可以很容易地與AD中的用戶和羣組玩耍!