Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable or Disable a User on Local Computer

Tags:

c#

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 ?

like image 529
user1528803 Avatar asked Dec 10 '25 21:12

user1528803


1 Answers

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:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

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!

like image 167
marc_s Avatar answered Dec 12 '25 10:12

marc_s