Windows 7和Vista UAC - 以编程方式请求C#中的提升

Chr*_*ris 22 c# uac windows-vista windows-7

我有一个程序,在极少数情况下只需要提升到Admin,所以我不想设置我的清单以要求永久性提升.

我怎样才能在我需要时以编程方式请求提升?

我正在使用C#

Chr*_*ris 26

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案,但是`RunElevated`可能应该返回一个`bool`,以便在用户取消提升时你可以抱怨. (4认同)
  • 此外,由于您将要关闭并重新启动应用程序,如果有状态要保存,请注意这一点.您可能更喜欢将需要提升的内容分区并在不关闭主应用程序的情况下启动提升. (3认同)