简体   繁体   English

c#比较当前的Windows用户与AD组

[英]c# comparing current windows user to AD group

I am trying to grab the current windows user and see if that user is part of a certain group in Active Directory. 我正在尝试获取当前的Windows用户,并查看该用户是否是Active Directory中某个组的一部分。 The username information finds "Harper\\TSmith" which seems fine but when I get to the 用户名信息找到“ Harper \\ TSmith”,看起来不错,但是当我进入

UserPrincipal uPrincipal = Psearch.FindOne() as UserPrincipal

Line UPrincipal is null. 行UPrincipal为空。 Can not figure out why. 想不通为什么。 I also have at the bottom a validator class that as a bool method to see if they are part of that particular group. 我还在底部有一个验证器类,作为bool方法,以查看它们是否属于该特定组。

PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain);
            UserPrincipal findUser = new UserPrincipal(principalCtx);
            //findUser.Name = Environment.UserName;
            findUser.Name = WindowsIdentity.GetCurrent().Name;
            PrincipalSearcher pSearch = new PrincipalSearcher();
            pSearch.QueryFilter = findUser;
            UserPrincipal uPrincipal = pSearch.FindOne() as UserPrincipal;

            Validator validate = new Validator();
            //validate.IsUserInGroup("VisualOne", uPrincipal);

            if (validate.IsUserInGroup("MyGroup", uPrincipal))
            {
                var MemberShipForm = new Membership();
                MemberShipForm.Show();
            }



public bool IsUserInGroup(string groupName, UserPrincipal user)
    {
        PrincipalContext context = new PrincipalContext(ContextType.Domain, "Harper");
        GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "MyGroup");

        if (user.IsMemberOf(group))
        {
            return true;
        }
        return false;
    }
PrincipalContext principalCtx = new PrincipalContext(ContextType.Domain);
UserPrincipal uPrincipal = UserPrincipal.Current;

 if (validate.IsUserInGroup("MyGroup", uPrincipal))
            {
                var MemberShipForm = new Membership();
                MemberShipForm.Show();
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM