How to determine if user account is enabled or disabled

你。 提交于 2019-11-26 19:05:18

问题


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 to a list view with check boxes.

I would like to default the listviewitems' default check state to depend upon the enabled/disabled state of the account.

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);
}

I'm struggling to find the right attribute to parse to get the state of the account from the DirectoryEntry object. I've searched for AD User attributes, but not found anything useful.

Can anyone offer any pointers?


回答1:


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);
}



回答2:


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
        }
    }
}



回答3:


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;
}


来源:https://stackoverflow.com/questions/2005637/how-to-determine-if-user-account-is-enabled-or-disabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!