How to determine if user account is enabled or disabled

Bryan picture Bryan · Jan 5, 2010 · Viewed 80k times · Source

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?

Answer

Dimi Takis picture Dimi Takis · Jan 5, 2010

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