Reputation: 474
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 ?
Upvotes: 0
Views: 745
Reputation: 5016
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.
Upvotes: 1
Reputation: 2397
"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.
Upvotes: 1