简体   繁体   English

保留管理员权限

[英]Keeping administrator privileges

I wrote a WinForms C# app that needs administrator privileges to work and also needs to start at computer startup (with registry). 我编写了一个WinForms C#应用程序,该应用程序需要管理员权限才能工作,并且还需要在计算机启动时启动(带有注册表)。

 RegistryKey reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
 reg.SetValue("My app", Application.ExecutablePath.ToString());

So I tried changing the manifest to requiredAdministrator and got an error about clickOnce, which I completely didn't understand. 因此,我尝试将清单更改为requiredAdministrator并收到有关clickOnce的错误,我完全不理解。 So I tried publishing the app and installing as administrator, but then when the application starts at startup it doesn't have the administrator privileges anymore. 因此,我尝试发布该应用程序并以管理员身份进行安装,但是当该应用程序在启动时启动时,它不再具有管理员权限。

Anyone knows how to get administrator privileges for good? 有谁知道如何永久获得管理员特权?

You can go to the shortcut => Properties => Advanced ... => check Run as administrator. 您可以转到快捷方式=>属性=>高级... =>选中以管理员身份运行。

Now you have configured your shortcut to start the application with administrator privileges. 现在,您已经配置了快捷方式以管理员权限启动应用程序。

What you need is permission elevation request. 您需要的是权限提升请求。 Usually it is done via manifest, or if you have just a process you can start it with elevated permissions. 通常,它是通过清单来完成的,或者如果您只有一个过程,则可以使用提升的权限来启动它。 This gives an explanation, and this explains how to embed the manifest. 给出了一个解释,并且解释了如何嵌入清单。

You can try to use self-elevating, no sure how it will looks for auto-starting application (same as @peer answer) 您可以尝试使用自动提升功能,无需确定自动启动应用程序的外观(与@peer答案相同)

// at application start
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);

// if not admin - elevate
if(!isAdmin)
{
    var info = new ProcessStartInfo(Application.ExecutablePath) { Verb = "runas" };
    Process.Start(info);
    return; // exit
}

// if we are here - application runs as admin
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM