25

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
  • 34,719
  • 24
  • 185
  • 251
Chris
  • 25,677
  • 44
  • 189
  • 332

1 Answers1

29
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.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;
}
Chris
  • 25,677
  • 44
  • 189
  • 332
  • 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