简体   繁体   中英

C# Get Administrator Rights For A Single Method

I have a Method/Event Form1_Load and i want to give it Administrator Rights

Because in that Method/Event i associate my program with my extension , Also don't want to start application as administrator , If i do that program will not work correcly

So i have a code :

[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]

private void Form1_Load(object sender, EventArgs e)
{
...
}

But not works And my application gives error :

UnauthorizedAccessException

How can i fix this ?

"associate my program with my extension": your design is wrong. That association is done when your program gets installed. And there it is no problem at all: the installer is running elevated.

You won't like this answer, but you can't elevate the user for one method, instead you need to request elevation for the entire application, when it loads.

Please see https://msdn.microsoft.com/en-us/library/bb756929.aspx?f=255&MSPPError=-2147217396 for how to do that.

This is also helpful https://code.msdn.microsoft.com/windowsapps/CSUACSelfElevation-644673d3

EDIT:

If you have one task to do, like associating an extension, then you can write the logic for that in a separate EXE that only does that task. Then you can launch that EXE from your main program with

 System.Diagnostics.Process.Start("<path to exe>");

Provided you have followed the advice in the link above, your EXE will run and request elevation, and should be able to do what you need.

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.

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