2010-03-16 68 views
3

下面是一些代碼:我(想)我想使用BItWise運算符來檢查useraccountcontrol屬性!

 DirectorySearcher searcher = new DirectorySearcher(); 
     searcher.Filter = "(&(objectClass=user)(sAMAccountName=" + lstUsers.SelectedItem.Text + "))"; 
     SearchResult result = searcher.FindOne(); 

在result.Properties [「的UserAccountControl」]將是這會給我取決於帳戶的狀態值的項目。例如,值爲66050意味着我正在處理: 正常帳戶;密碼未過期;已被禁用。 Explanation here

什麼是找出最簡潔的方式,如果我的價值「包含」 ACCOUNTDISABLE標誌(即2)

提前感謝!

回答

5
Convert.ToBoolean((int)result.Properties["useraccountcontrol"] & 0x0002) 

從當前的代碼庫在這裏翻譯,它應該工作...

+0

所有好的答案,到目前爲止,但由於弗蘭克 - 我想你是第一個! – BIDeveloper 2010-03-16 17:01:04

4
enum AccountFlags 
{ 
    Script = (1<<0), 
    AccountDisable = (1<<1), 
    // etc... 
} 

if(((int)result.Properties["useraccountcontrol"]) & AccountFlags.AccountDisable > 0) 
{ 
    // Account is Disabled... 
} 
2

這是一般(via)大tutorial for Active Directory via C#

基本上要與&操作者檢查數量:

if((result & ACCOUNTDISABLE) == ACCOUNTDISABLE) 
{ .... } 

您可以定義ACCOUNTDISABLE作爲一個常量(如表中的你的鏈接)。或者你爲值創建一個枚舉。確保分配正確的數字並設置[Flags]-attribute
您選擇什麼取決於您需要多少個值。當只處理ACCOUNTDISABLE而不處理其他事情時,定義或常量將會執行。

3
UserAccountControlFlags userAccFlags = (UserAccountControlFlags) 66050; 

// Much more readable  
if(userAccFlags.Has(UserAccountControlFlags.AccountDisabled)) 
{ 
    // Do your stuff here 
} 

而這裏的擴展方法:從C# Online

[Flags] 
public enum UserAccountControlFlags 
{ 
    Script        = 0x1, 
    AccountDisabled     = 0x2, 
    HomeDirectoryRequired    = 0x8, 
    AccountLockedOut     = 0x10, 
    PasswordNotRequired    = 0x20, 
    PasswordCannotChange    = 0x40, 
    EncryptedTextPasswordAllowed  = 0x80, 
    TempDuplicateAccount    = 0x100, 
    NormalAccount      = 0x200, 
    InterDomainTrustAccount   = 0x800, 
    WorkstationTrustAccount   = 0x1000, 
    ServerTrustAccount     = 0x2000, 
    PasswordDoesNotExpire    = 0x10000, 
    MnsLogonAccount     = 0x20000, 
    SmartCardRequired     = 0x40000, 
    TrustedForDelegation    = 0x80000, 
    AccountNotDelegated    = 0x100000, 
    UseDesKeyOnly      = 0x200000, 
    DontRequirePreauth     = 0x400000, 
    PasswordExpired     = 0x800000, 
    TrustedToAuthenticateForDelegation = 0x1000000, 
    NoAuthDataRequired     = 0x2000000 
} 
1

根據您的需求簡稱

public static bool Has<T>(this System.Enum type, T value) where T : struct 
{ 
    return ((int)(object)type & (int)(object)value) > 0; 
} 

枚舉的定義,你可以使用ActiveDirectory中通過啓用過濾賬戶/禁用狀態:

searcher.Filter = "(&(objectClass=user)(UserAccountControl:1.2.840.113556.1.4.803:=2))"; 

或:

searcher.Filter = "(&(objectClass=user)(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))"; 

相關MS KB文章:http://support.microsoft.com/kb/269181

而另一篇文章:http://www.windowsserverfaq.org/?url=/faq/ADQueries/LDAP-Queries.asp

+0

+1查詢級別的位運算符。不是問題的確切答案,而是最常用的答案:D – 2017-09-10 21:20:40