How to determine if user account is enabled or disabled

后端 未结 4 751
野性不改
野性不改 2020-12-04 13:54

I am throwing together a quick C# win forms app to help resolve a repetitive clerical job.

I have performed a search in AD for all user accounts and am adding them t

相关标签:
4条回答
  • 2020-12-04 14:26

    I came here looking for an answer, but it was only for DirectoryEntry. So here is a code that works for SearchResult / SearchResultCollection, for people who had the same problem:

    private bool checkIfActive(SearchResult sr)
    {
        var vaPropertiy = sr.Properties["userAccountControl"];
    
        if (vaPropertiy.Count > 0) 
        {
            if (vaPropertiy[0].ToString() == "512" || vaPropertiy[0].ToString() == "66048") 
            {
                return true;
            } 
            
            return false;
        }
    
        return false;
    }
    
    0 讨论(0)
  • 2020-12-04 14:27

    Using System.DirectoryServices.AccountManagement: domainName and username must be the string values of the domain and username.

    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 讨论(0)
  • 2020-12-04 14:45

    Not that anyone asked, but here's a java version (since I ended up here looking for one). Null checking is left as an exercise for the reader.

    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 讨论(0)
  • 2020-12-04 14:49

    this code here should work...

    private bool IsActive(DirectoryEntry de)
    {
      if (de.NativeGuid == null) return false;
    
      int flags = (int)de.Properties["userAccountControl"].Value;
    
      return !Convert.ToBoolean(flags & 0x0002);
    }
    
    0 讨论(0)
提交回复
热议问题