gpt4 book ai didi

c# - 使用 C# 检测用户是否是 Windows 8 中的管理员

转载 作者:行者123 更新时间:2023-11-30 17:10:36 25 4
gpt4 key购买 nike

我有一些代码适用于大多数 Windows 版本,用于检测当前用户是否以管理员身份运行。我已经看到我们的客户使用组策略的问题,但这是行不通的。现在我已经将我的工作站升级到 Windows 8,代码不再有效。这是代码:

[DllImport("advapi32.dll")]
private static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
private const int Logon32LogonInteractive = 2;
private const int Logon32ProviderDefault = 0;

public void Run() {
var _token;
LogonUser(Username, Domain, Password, Logon32LogonInteractive, Logon32ProviderDefault, ref _token);
_windowsIdentity = new WindowsIdentity(_token);
WindowsPrincipal myPrincipal = new WindowsPrincipal(_windowsIdentity);
var isAdmin = myPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}

在这种情况下,isAdmin 在应该为真时却为假。如果有人知道执行此检查的正确方法,并且适用于所有版本的 Windows,那就太好了。如果有人知道如何更改此代码以使其在使用组策略的域中工作,那就更好了。

我试图从我的类(class)中复制适当的代码。显然这不会编译,但如果我遗漏了什么,请告诉我。

谢谢!

最佳答案

如果在 Windows Vista 及更高版本上启用了 UAC,您的代码将无法运行。至quote the documentation :

Note: In Windows Vista, User Account Control (UAC) determines the privileges of a user. If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. By default, you are in the standard user role. When you attempt to perform a task that requires administrative privileges, you can dynamically elevate your role by using the Consent dialog box. The code that executes the IsInRole method does not display the Consent dialog box. The code returns false if you are in the standard user role, even if you are in the Built-in Administrators group. You can elevate your privileges before you execute the code by right-clicking the application icon and indicating that you want to run as an administrator.

isAdmin 将为 false,除非用户正在提升运行。您可能会看到这个问题:In .NET/C# test if process has administrative privileges了解更多。

对于您想做的特定事情,您可能会尝试使用命令式或声明式安全要求,而不是检查组成员资格。如果您缺少所需的权限,这些将抛出 SecurityException,您可以捕获然后处理。

关于c# - 使用 C# 检测用户是否是 Windows 8 中的管理员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12042916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com