.net 如何检查给定用户是否是内置Administrators组的成员?

.net 如何检查给定用户是否是内置Administrators组的成员?,.net,security,.net,Security,我需要以编程方式(在.NET中)检查给定用户(域帐户)是否是当前计算机(执行应用程序的计算机)上内置Administrators组的成员 有可能吗?你可以像我在这个答案中那样循环分组: 阅读更多内容后,最简单的方法是使用System.DirectoryServices.AccountManagement名称空间。以下是如何使用它: 样本: public static bool IsUserInGroup(string username, string groupname, ContextTy

我需要以编程方式(在.NET中)检查给定用户(域帐户)是否是当前计算机(执行应用程序的计算机)上内置Administrators组的成员


有可能吗?

你可以像我在这个答案中那样循环分组:

阅读更多内容后,最简单的方法是使用
System.DirectoryServices.AccountManagement
名称空间。以下是如何使用它:

样本:

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);
}

我不了解.Net,但在win32中,最简单的方法是调用IsUserAnAdmin()。如果需要更多控制,可以打开流程令牌并使用CheckTokenMembership检查需要检查的每个组


编辑:请参阅.NET示例代码(感谢chopeen)

有一个Win32 API,您可以调用:


Vista上的问题更复杂。。。查看此图。

如果您谈论的是当前正在运行的用户,则

using System.Security.Principal;

WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal wp = new WindowsPrincipal(identity);

if (wp.IsInRole("BUILTIN\Administrators"))
   // Is Administrator
else
   // Is Not

如果不是,我希望可以为特定用户设置标识,但不了解如何设置。

“IsUserAnAdmin函数是CheckTokenMembership的包装器。建议直接调用该函数以确定管理员组状态,而不是调用IsUserAnAdmin”。(从链接页面)我以前没有注意到这个警告。我想知道为什么微软会考虑贬低这样一个简单的帮手…幸运的是,他们在向后兼容性方面有良好的记录。System.DirectoryServices.AccountManagement命名空间是.NET 3.5的新名称空间,不是吗?链接文章中的第一句话:“浏览一些新的3.5内容时,我偶然发现了一个名为“System.DirectoryServices.AccountManagement”的新程序集,它引起了我的注意。”对不起,我错过了。您能在您的答案中添加信息以使其完整(以便我可以将其标记为已接受答案)吗?