如何检查 windows 帐户在 C# 中是否被禁用?

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

我正在尝试检查 window 帐户是否在活动目录中被禁用,因此我尝试了 System.DirectoryServices.AccountManagement 命名空间但找不到任何方法来检查帐户是否被禁用,这与 IsAccountLockedOut 不同方法。

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

我们使用这个方法:

        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 - 是一种扩展方法:

    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);
    }

因此,获取您帐户的 DirectoryEntry 并调用此方法。

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