Search This Blog

Wednesday, October 31, 2012

How to lock an Active Directory account with C#

There are a lot of answers out there to how to lock an account using ADSI -- some just wrong, others dangerously wrong.

This one works cleanly, transparently, and well:

private void LockAccount()
{

string _userAccountWithoutDomain = “test”;
string _domainName = “IND”;
string _userBadPassword = “yyyyy”; // password should be incorrect
int _passwordExpiryPolicy = 3;
string _connectionPrefix = “LDAP://” + _domainName;

for (int i = 0; i < _passwordExpiryPolicy; i++)
{

try {
new DirectoryEntry(_connectionPrefix, _userAccountWithoutDomain, _userBadPassword).RefreshCache(); }
catch (Exception)
{ }
}
}

Thanks to Sanjiv at http://sanjivblog.wordpress.com/2011/05/13/how-to-lock-the-ad-active-directory-account-programmatically-in-c/

No comments: