C# 单一方法的管理员权限
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2021831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Admin rights for a single method
提问by lluismontero
Is it possible to require administrator rights for one single method?
是否可以为一种方法要求管理员权限?
Something like this:
像这样的东西:
[RequireAdminRightsForThisMethod()]
private void TheMethod(){
// Do something
}
采纳答案by Dirk Vollmar
You can add a PrincipalPermission
attribute to your method to demand administrative privileges for its execution:
您可以PrincipalPermission
向您的方法添加一个属性以要求其执行的管理权限:
[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
public void MyMethod()
{
}
This is described in more detail in the following article:
这在以下文章中有更详细的描述:
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.
如果您正在寻找提升现有进程的方法,我怀疑这是否可行,因为在启动时将进程级别的管理员权限授予进程(请参阅此相关问题)。您必须以“管理员身份”运行您的应用程序才能获得所需的行为。
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:
但是,有一些技巧可以让您为所欲为,但请注意,这可能会带来严重的安全风险。请参阅 MSDN 论坛中的以下主题:
Launching MyElevatedCom Server without prompting Administrator credentialls from Standard User
Update (from comment)
更新(来自评论)
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();
回答by SLaks
A method can require administrative privileges to run, but it's not possible to automatically elevate to Admin when executing a method.
方法可能需要管理权限才能运行,但在执行方法时不可能自动提升为管理员。