Ch Rashid Ebad
Ch Rashid Ebad

Reputation: 3

How to check that windows account is disabled in C#?

I am trying to check if window account is disabled or not in active directory, for this reason I tried System.DirectoryServices.AccountManagement namespace but could not find any method to check if account is disable unlike IsAccountLockedOut method.

PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal =UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
oUserPrincipal.IsAccountLockedOut();

Upvotes: 0

Views: 738

Answers (2)

user5308911
user5308911

Reputation: 11

PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal =UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);

bool? IsEnabled = oUserPrincipal.Enabled;

// if IsEnabled = true then User Account is Enabled

// if IsEnabled = false then User Account is Disabled

Upvotes: 1

Backs
Backs

Reputation: 24903

We use this method:

        var context = new DirectoryContext(DirectoryContextType.Domain, "domain");

        using (var domainController = DomainController.FindOne(context))
        {
            using (var directorySearcher = domainController.GetDirectorySearcher())
            {
                directorySearcher.Filter = String.Format("(sAMAccountName={0})", "login");
                directorySearcher.SizeLimit = 1;
                var userDirectory = directorySearcher.FindOne();
                using (var userDirectoryEntry = userDirectory.GetDirectoryEntry())
                {
                    var active = userDirectoryEntry.IsActive();
                }
            }
        }

IsActive - is an extension method:

    public static bool IsActive(this DirectoryEntry directoryEntry)
    {
        if (directoryEntry.NativeGuid == null) return false;

        var value = directoryEntry.Properties["userAccountControl"].Value;
        if (value == null)
            return true;

        var flags = (int)value;

        return !Convert.ToBoolean(flags & 0x0002);
    }

So, get DirectoryEntry of your account and call this method.

Upvotes: 1

Related Questions