1

我试图通过搜索用户的电子邮件地址并检查 Enabled 属性来查找用户是否拥有 Active Directory 帐户(如果我返回 Enabled 作为 true - 运行代码,如果我返回 false - 运行其他代码,如果结果是null - 返回 false,因为该电子邮件不再存在)。当我进入 foreach 循环时,它已经根据他们在result中的电子邮件找到了用户,但是使用 if 和 elses 进行检查会将用户返回为 NULL。

    public static bool DoesUserExist(string email, string domain)
    {
        var found = false;

        using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain))
        {
            UserPrincipal user = new UserPrincipal(domainContext);
            user.EmailAddress = email;

            PrincipalSearcher search = new PrincipalSearcher(user);
            search.QueryFilter = user;

            PrincipalSearchResult<Principal> results = search.FindAll();

            foreach (Principal result in results)
            {
                if (user.Enabled == true)
                {
                    found = false;
                    Helpers.LogMessage("Active Directory Account is Enabled in " + domain + " domain");
                }
                else if (user.Enabled == false)
                {
                    found = true;
                    Helpers.LogMessage("Active Directory User Account is Disabled in " + domain + " domain");   
                }
                else if (user.Enabled == null)
                {
                    found = true;
                    Helpers.LogMessage("No Active Directory Account Found in " + domain + " domain");
                }
            }

            return found;
        }
    }

如果用户在 foreach 中启用或禁用,我缺少什么能够访问?

4

1 回答 1

1

您的问题是用户与您的搜索结果或循环无关;它只是搜索的模板。另请注意,如果没有找到结果,您将不会进入循环(results将为空),因此测试 fornull没有任何意义。另外,您的found设置似乎是错误的。

if (!results.Any())
    Helpers.LogMessage("No Active Directory Account Found in " + domain + " domain");
else {
    var found = false;

    foreach (UserPrincipal result in results) {
        found = !result.Enabled;
        if (found)
            Helpers.LogMessage("Active Directory User Account is Disabled in " + domain + " domain");   
        else
            Helpers.LogMessage("Active Directory Account is Enabled in " + domain + " domain");
    }
}
于 2017-06-19T22:44:19.273 回答