我正在尝试确定是否启用了 AD 中的用户帐户。为此,我使用以下代码:
string domain = "my domain";
string group = "my security group";
string ou = "my OU";
//init context
using (var cnt= new PrincipalContext(ContextType.Domain, domain))
{
    //find the necessary security group
    using (GroupPrincipal mainGroup 
              = GroupPrincipal.FindByIdentity(cnt, IdentityType.Guid, group))
    {
        if (mainGroup != null)
        {
            //get the group's members
            foreach (var user in mainGroup.GetMembers()
                                   .OfType<UserPrincipal>()
                                   .Where(u => u.DistinguishedName.Contains(ou)))
            {
                //ensure that all the info about the account is loaded
                //by using FindByIdentity as opposed to GetMembers
                var tmpUser= UserPrincipal.FindByIdentity(cnt, 
                                                          user.SamAccountName);
                //actually I could use `user` variable, 
                //as it gave the same result as `tmpUser`.
                //print the account info
                Console.WriteLine(tmpUser.Name + "\t" + 
                                  tmpUser.Enabled.HasValue + "\t" + 
                                  tmpUser.Enabled.Value);                    
            }
        }
    }
}
问题是,当我在管理帐户下运行此代码时,我得到了真正的结果,而当我在非特权帐户下运行它时,会user.Enabled返回false一些帐户,而应该是true.
我设法找到的唯一类似的问答是
- 对于实际上已启用的帐户,UserPrincipal.Enabled 返回 False?
- 通过 C#.NET 3.5 在 Active Directory 中的所有内容(使用 System.DirectoryServices.AccountManagement)
这在这里没有帮助。
为什么呢?我有哪些选择可以在非特权帐户下获取此信息?
这是另一种方法:如何确定用户帐户是启用还是禁用:
private bool IsActive(DirectoryEntry de)
{
    if (de.NativeGuid == null) 
        return false;
    int flags = (int)de.Properties["userAccountControl"].Value;
    if (!Convert.ToBoolean(flags & 0x0002)) 
        return true; 
    else 
        return false;
}
Active Directory 对象和 C#中描述了相同的方法。
但是,当在非特权用户帐户下运行时,userAccountControl属性是null并且无法确定帐户的状态。
此处的解决方法是使用PrincipalContext Constructor,指定具有足够权限访问 AD 的用户的凭据。
我仍然不清楚,为什么非特权用户可以访问 AD,并且无法获取某些帐户属性的值。可能这和C#无关,应该在AD中配置...