26

I have a program that only requires elevation to Admin on very rare occasions so I do not want to set-up my manifest to require permanent elevation.

How can I Programmatically request elevation only when I need it?

I am using C#

Cœur
  • 37,241
  • 25
  • 195
  • 267
Chris
  • 26,744
  • 48
  • 193
  • 345

1 Answers1

30
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = principal.IsInRole(WindowsBuiltInRole.Administrator);

if (!hasAdministrativeRight)
{
    RunElevated(Application.ExecutablePath);
    this.Close();
    Application.Exit();
}

private static bool RunElevated(string fileName)
{
    //MessageBox.Show("Run: " + fileName);
    ProcessStartInfo processInfo = new ProcessStartInfo();
    processInfo.Verb = "runas";
    processInfo.FileName = fileName;
    try
    {
        Process.Start(processInfo);
        return true;
    }
    catch (Win32Exception)
    {
        // Do nothing. Probably the user canceled the UAC window
    }
    return false;
}
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
Chris
  • 26,744
  • 48
  • 193
  • 345
  • 4
    This is the right answer, but `RunElevated` should probably return a `bool` so that you can complain if the user canceled elevation. –  Feb 17 '10 at 19:49
  • 3
    Also, since you're going to be closing and restarting the app, if there is state to save, take care of that. You may prefer to partition out the stuff that needs elevation and launch that elevated without closing the main app. – Kate Gregory Jan 25 '11 at 19:24
  • 1
    Running this on Win10 in 2022, I found that I had to add `processInfo.UseShellExecute = true` to get the UAC window. (Aside from that, no complaints!) – Petter Hesselberg Nov 15 '22 at 19:05