Search code examples
c#active-directory

Enable/Disable AD user with LDAP


Is it possible to enable (or disable) a user in Active Directory with LDAP command?

And also, is it possible doing it with C#?

I've already looked here and here

Thanks,

J


Solution

  • You can use PrincipalContext to enable/ disable AD account. To Enable the AD you can do something like this:

     private static void EnableADUserUsingUserPrincipal(string username)
         {
           try
        {                
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
    
            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                    (principalContext, username);
    
            userPrincipal.Enabled = true;
    
            userPrincipal.Save();
    
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
     }
    

    To disable Active Directory you can just set the userPrincipal.Enabled = false;