Disable the Account

The FindByIdentity overload method on the user principal object locates the user object of the account to disable. The user account is then disabled by setting the System.DirectoryServices.AccountManagement.AuthenticablePrincipal.Enabled property to false. Finally, the changes are saved in the store.

        internal static bool DisableTheAccount(string user)
        {
            // Creating the PrincipalContext
            PrincipalContext principalContext = null;
            try
            {
                principalContext = new PrincipalContext(ContextType.Domain, "fabrikam", "DC=fabrikam,DC=com");
            }
            catch (Exception e)
            {
                MessageBox.Show("Failed to create PrincipalContext. Exception: " + e);
                Application.Exit();
            }

            // Disabling the user account
            bool bReturn = false;
            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, user);

            if (userPrincipal != null)
            {
                userPrincipal.Enabled = false;
                try
                {
                    userPrincipal.Save();
                    bReturn = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show("Exception when disabling the account. " + e);
                }
            }

            return bReturn;
        }

See Also

Reference

System.DirectoryServices.AccountManagement

Concepts

About System.DirectoryServices.AccountManagement
Using System.DirectoryServices.AccountManagement

Send comments about this topic to Microsoft.

Copyright © 2008 by Microsoft Corporation. All rights reserved.