How to check if a given user is a member of the built-in Administrators group?

后端 未结 4 1723
刺人心
刺人心 2021-01-15 03:28

I need to check programmatically (in .NET) whether a given user (domain account) is a member of the built-in Administrators group on a current computer (the one where the ap

4条回答
  •  情书的邮戳
    2021-01-15 03:52

    You could loop the groups like i did in this answer:

    Determining members of local groups via C#

    After reading some more, the easiest thing would be to use the System.DirectoryServices.AccountManagement namespace. Here is how it can be used:

    http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx

    Sample:

    public static bool IsUserInGroup(string username, string groupname, ContextType type)
    {
        PrincipalContext context = new PrincipalContext(type);
    
        UserPrincipal user = UserPrincipal.FindByIdentity(
            context,
            IdentityType.SamAccountName,
            username);
        GroupPrincipal group = GroupPrincipal.FindByIdentity(
            context, groupname);
    
        return user.IsMemberOf(group);
    }
    

提交回复
热议问题