I have to lock user accounts in Active Directory programmatically in C#.
Unfortunately it doesn’t work via the userAccountControl attribute. Every time I set userAccountControl to 528 (=normal account w/ lockout flag), Active Directory won’t accept the value and resets it without further notice to 512 (=normal account).
Now I tried to lock the account by providing incorrect credentials (see below), but this doesn’t work either.
int retries = 0; while (!adsUser.IsAccountLocked && retries < MAX_LOCK_RETRIES) { retries++; try { new DirectoryEntry(userPath, logonName, incorrectPassword).RefreshCache(); } catch (Exception) { /* ... */ } adsUser.GetInfo(); }
Any ideas?
Make sure the account you’re using to disable the account has sufficient privileges to disable accounts. See this example from Microsoft.