To enable or disable a user on local computer, I am using the following snippet.
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry currentUser = localMachine.Children.Find(user, "Administrators");
currentUser.Invoke("AccountDisabled", new object[] { true });
currentUser.CommitChanges();
I am assigning user as a string. I am getting a "filepath not found error": Comexception Unhandled.
Is anything wrong with my code ?
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Basically, you can define a machine-level context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
user.Enabled = false;
user.Save();
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With