如何检查系统上的每个用户是否在 C# 中都具有管理员权限 [英] How to check if every users on the system has administrator rights in C#

查看:42
本文介绍了如何检查系统上的每个用户是否在 C# 中都具有管理员权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在我的系统中创建的用户列表:

I have a list of users created in my system:

  • 管理员(默认)
  • 客人
  • User1(标准用户)
  • User2(管理员用户)

我想知道在 C# 中通过 WMI 赋予所有这些用户的权限,这怎么可能?还有其他方法可以找到它们.即使一个用户拥有此权限,它也必须退出循环

I want to know the rights given to all these users in C# through WMI ,how is this possible??Is there any other way to find them. Even If one user has this right it must exit from the loop

我使用以下代码:

WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (isAdmin == true)
{
    current_logged_user = "Yes";
}
else
{
    current_logged_user = "No";
}

这仅给我当前登录的信息,但我需要所有用户

This gives me only the currently logged info,but I need for all the users

链接

以下链接仅提供管理员成员链接

The below link just give the members of administrartors link

推荐答案

你应该能够通过 WMI 返回所有用户

You should be able to return all users via WMI with

        string groupNameToSearchFor = "Administrators"; // can be any group,maybe better to use something like builtin.administrators

        using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, null))
        {
            ManagementObjectSearcher usersSearcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_UserAccount");
            ManagementObjectCollection users = usersSearcher.Get();

            foreach (ManagementObject user in users)
            {
                if ((bool)user["LocalAccount"] == true && int.Parse(user["SIDType"].ToString()) == 1)
                {
                    var userPrincipal = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, user["Name"].ToString());
                    GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, groupNameToSearchFor);
                    MessageBox.Show("Is User admin? -> " + (bool)userPrincipal.IsMemberOf(gp));

                }
            }
        }

你必须包括

using System.DirectoryServices.AccountManagement;
using System.Management;

还要检查用户是否真的是用户而不是不同的对象(不确定我的检查是否足够).

And also check if the user is really a user and not a different object (not sure if my checks are enough).

您可以使用

        var localUsers = users.Cast<ManagementObject>().Where(
            u => (bool)u["LocalAccount"] == true &&
                 (bool)u["Disabled"] == false &&
                 (bool)u["Lockout"] == false &&
                 int.Parse(u["SIDType"].ToString()) == 1 &&
                 u["Name"].ToString() != "HomeGroupUser$");

这篇关于如何检查系统上的每个用户是否在 C# 中都具有管理员权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆