How to elevate .net application permissions?

情到浓时终转凉″ 提交于 2019-12-20 04:24:34

问题


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 task can't be performed by Standard Users under normal scenarios.

I tried creating a service to do the update process but I had some security issues and I asked this question about it in superusers.

Now, considering the fact that most applications require elevated privileges to perform such task I think that might be the right approach. But how do I request elevation for the updater under all Windows version as of XP, included. I've found many topics about a manifest file, but since I need this to work with XP I can't create a solution specifically for UAC.


回答1:


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.



来源:https://stackoverflow.com/questions/7351429/how-to-elevate-net-application-permissions

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