单一方法的管理员权限 [英] Admin rights for a single method

查看:25
本文介绍了单一方法的管理员权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对一种方法要求管理员权限?

Is it possible to require administrator rights for one single method?

像这样:

[RequireAdminRightsForThisMethod()]

private void TheMethod(){

    // Do something

}

推荐答案

您可以添加 PrincipalPermission 属性到您的方法以要求其执行的管理权限:

You can add a PrincipalPermission attribute to your method to demand administrative privileges for its execution:

[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTINAdministrators")]
public void MyMethod()
{
}

以下文章对此进行了更详细的描述:

This is described in more detail in the following article:

C# .Net 中的安全原则和本地管理员权限

如果您正在寻找提升现有进程的方法,我怀疑这是可能的,因为在启动时将进程级别的管理员权限授予进程(请参阅此相关问题).您必须以管理员身份"运行您的应用程序才能获得所需的行为.

If you are looking for a way to elevate an already existing process I doubt that this is possible as administrator privileges are given on process-level to a process upon startup (see this related question). You would have to run your application "as administrator" to get the desired behavior.

但是,有一些技巧可以让您为所欲为,但请注意,这可能会带来严重的安全风险.请参阅 MSDN 论坛中的以下主题:

However, there are some tricks that might allow you to do what you want, but be warned that this might open up severe security risks. See the following thread in the MSDN forums:

启动MyElevatedCom Server 不提示来自标准用户的管理员凭据

更新(来自评论)

似乎如果更新需要提升您的应用程序更新最好由单独的进程完成(另一个可执行文件,或者您的应用程序使用命令行开关调用).对于那个单独的过程,您可以按如下方式请求提升:

It seems that if an update requires elevation your application update is best done by a separate process (either another executable, or your application called with a command line switch). For that separate process you can request elevation as follows:

var psi = new ProcessStartInfo();
psi.FileName = "path to update.exe";
psi.Arguments = "arguments for update.exe";
psi.Verb = "runas";

var process = new Process();
process.StartInfo = psi;
process.Start();   
process.WaitForExit();

这篇关于单一方法的管理员权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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