2010-01-05 72 views
49

我將一個快速的C#win表單應用程序放在一起,以幫助解決重複性的文書工作。如何確定用戶帳戶是啓用還是禁用

我已在AD中爲所有用戶帳戶執行搜索,並將它們添加到帶有複選框的列表視圖中。

我想默認listviewitems的默認檢查狀態取決於帳戶的啓用/禁用狀態。

string path = "LDAP://dc=example,dc=local"; 
DirectoryEntry directoryRoot = new DirectoryEntry(path); 
DirectorySearcher searcher = new DirectorySearcher(directoryRoot, 
    "(&(objectClass=User)(objectCategory=Person))"); 
SearchResultCollection results = searcher.FindAll(); 
foreach (SearchResult result in results) 
{ 
    DirectoryEntry de = result.GetDirectoryEntry(); 
    ListViewItem lvi = new ListViewItem(
     (string)de.Properties["SAMAccountName"][0]); 
    // lvi.Checked = (bool) de.Properties["AccountEnabled"] 
    lvwUsers.Items.Add(lvi); 
} 

我很努力地找到正確的屬性來解析從DirectoryEntry對象獲取帳戶的狀態。我搜索了AD User attributes,但沒有找到任何有用的東西。

任何人都可以提供任何指針?

回答

85

這裏的代碼應該工作...

private bool IsActive(DirectoryEntry de) 
{ 
    if (de.NativeGuid == null) return false; 

    int flags = (int)de.Properties["userAccountControl"].Value; 

    return !Convert.ToBoolean(flags & 0x0002); 
} 
+0

完美謝謝。 – Bryan 2010-01-05 11:36:10

+21

該死的,你快,但這是一個鏈接關於所有的標誌是什麼意思:http://msdn.microsoft.com/en-us/library/ms680832.aspx – Oliver 2010-01-05 11:47:47

+0

thx您的評論:) +1 – 2010-01-05 11:48:48

5

不是說沒有人問過,但這裏有一個Java版本(因爲我結束了在這裏尋找一個)。空檢查留給讀者練習。

private Boolean isActive(SearchResult searchResult) { 
    Attribute userAccountControlAttr = searchResult.getAttributes().get("UserAccountControl"); 
    Integer userAccountControlInt = new Integer((String) userAccoutControlAttr.get()); 
    Boolean disabled = BooleanUtils.toBooleanObject(userAccountControlInt & 0x0002); 
    return !disabled; 
} 
+0

Upvote花時間分享,因爲標題不是語言特定的,這可能確實有助於某人。 – allen1 2015-06-26 17:54:41

5

使用System.DirectoryServices.AccountManagement: 域名,並用戶名必須是域和用戶名的字符串值。

using (var domainContext = new PrincipalContext(ContextType.Domain, domainName)) 
{ 
    using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, username)) 
    { 
     if (foundUser.Enabled.HasValue) 
     { 
      return (bool)foundUser.Enabled; 
     } 
     else 
     { 
      return true; //or false depending what result you want in the case of Enabled being NULL 
     } 
    } 
} 
+0

'((UserPrincipal)foundUser).Enabled == true'是對我有用的 – 2016-05-04 22:13:19

相關問題