How to elevate .net application permissions?

爱⌒轻易说出口 提交于 2019-12-02 06:05:20

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!