C# – Forced the application to have the administrator privileges


I need to give my application administrator rights, knowing that it will be run from a user session and not admin account.

I've looked on other sites, but can't find anything that helps.

I tried editing the manifest among other things and there have inserted the line:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

This gave me an error when trying to publish using ClickOnce, but not when I debug.

Can you help me?

Best Solution

first of all - indeed, it's not allowed by design, to install and ClickOnce app as admin: http://msdn.microsoft.com/en-us/library/142dbbz4(v=vs.90).aspx

take a look at this post: http://antscode.blogspot.ca/2011/02/running-clickonce-application-as.html - it explains how to run ClickOnce app as admin. BUT - it have to say that I have walked this path - and I did not have much luck with it. I had numerous troubles with this approach (trying to run ClickOnce app with admin privileges). As far as I recall, the biggest problem was auto-update was not working properly. Not to mention that non-admin users might need to enter admin credentials all the time.

So my advise would be to rethink your logic, and encapsulate the piece you need to be done as admin in a separate EXE file - and make it very clear for a user that when he clicks THAT button, UAC prompt will show up (probably by addin "shield" icon to the button). And in that button_click event do something like this:

// 2. Run Photoshop action on this image (and wait for the task to complete)
if (string.IsNullOrWhiteSpace(this.PhotoshopEnhanceActionAbsPath) == false)
    var pi = new ProcessStartInfo(this.PhotoshopEnhanceActionAbsPath,  "\"" + imgPhotoshopActionAbsPath + "\"");
    pi.UseShellExecute = true;
    pi.Verb = "runas";
    var photoshopAction = Process.Start(pi);
    var success = photoshopAction.WaitForExit();
    if (success == false)
        // do something here

this approach worked very well for me. The key here is this:

pi.UseShellExecute = true;
pi.Verb = "runas";

it runs your EXE with admin right - so UAC prompt will be displayed at that moment. Another nice consequence here is that users might not run this particular piece of logic each time they are using the app - and therefore they won't be annoyed by the prompt when they do not need it.