I wrote a WinForms C# app that needs administrator privileges to work and also needs to start at computer startup (with registry).
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. 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.
You can try to use self-elevating, no sure how it will looks for auto-starting application (same as @peer answer)
// 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
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.