How to elevate .net application permissions?

后端 未结 1 1083
栀梦
栀梦 2021-01-22 12:08

I have an application that would check for updates upon start and, if updates are found, it would copy some files over the network to the program files folder. Obviously such ta

1条回答
  •  旧时难觅i
    2021-01-22 12:35

    Privileges can only be elevated at startup for a process; a running process' privileges cannot be elevated. In order to elevate an existing application, a new instance of the application process must be created, with the verb “runas”:

    private static string ElevatedExecute(NameValueCollection parameters)
    {
        string tempFile = Path.GetTempFileName();
        File.WriteAllText(tempFile, ConstructQueryString(parameters));
    
        try
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.UseShellExecute = true;
            startInfo.WorkingDirectory = Environment.CurrentDirectory;
            Uri uri = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase);
            startInfo.FileName = uri.LocalPath;
            startInfo.Arguments = "\"" + tempFile + "\"";
            startInfo.Verb = "runas";
            Process p = Process.Start(startInfo);
            p.WaitForExit();
            return File.ReadAllText(tempFile);
        }
        catch (Win32Exception exception)
        {
            return exception.Message;
        }
        finally
        {
            File.Delete(tempFile);
        }
    }
    

    After the user confirms the execution of the program as administrator, another instance of the same application is executed without a UI; one can display a UI running without elevated privileges, and another one running in the background with elevated privileges. The first process waits until the second finishes its execution. For more information and a working example you can check out the MSDN archive.

    To prevent all this dialog shenanigans in the middle of some lengthy process, you'll need to run your entire host process with elevated permissions by embedding the appropriate manifest in your application to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.

    0 讨论(0)
提交回复
热议问题