如何检查C#中是否禁用了Windows帐户?

时间:2015-09-08 07:09:14

标签: c# active-directory

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

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

2 个答案:

答案 0 :(得分:1)

我们使用这种方法:

        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并调用此方法。

答案 1 :(得分:1)

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