[ACCEPTED]-Giving application elevated UAC-uac

Accepted answer
Score: 32

You don't need to meddle with all that to 8 make sure that your application always runs 7 with elevated privileges. You can simply 6 add an application manifest which instructs Windows to run your app 5 elevated, and the UAC prompt will appear 4 without you needing to write a single line 3 of code.

There's a related question with 2 an answer that also describes how to add 1 a manifest here: How can I embed an application manifest into an application using VS2008?

Score: 4

Move the WindowsPrincipal code from your 4 Form to Program.cs as in the example below. This 3 will prompt the user for UAC authority prior 2 to launching any forms and will only launch 1 the form if UAC authority has been granted.

        static void Main()
            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);

            if (!hasAdministrativeRight)
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = Application.ExecutablePath;
                startInfo.Verb = "runas";
                    Process p = Process.Start(startInfo);
                catch (System.ComponentModel.Win32Exception ex)
                    MessageBox.Show("This utility requires elevated priviledges to complete correctly.", "Error: UAC Authorisation Required", MessageBoxButtons.OK);
//                    Debug.Print(ex.Message);
                Application.Run(new Form1());
Score: 3

Elevating your privileges is always going 13 to start a new process. There is no way 12 around that, other than starting with elevated 11 privileges in the first place by setting 10 your application to require administrative 9 privileges. What you can do is end the application 8 right after the elevated process starts, so 7 that you only have one application running.

This 6 scenario is usable for applications that 5 only require certain parts of their function 4 to be elevated - such as an automatically 3 self-updating installer that needs access 2 to Program Files - and not one that requires 1 administrative access all the time.

Score: 3

This is a much better approach when your application 2 is known to require Admin privileges from 1 the start.

More Related questions