Using UAC to request Administrative Privileges from c#


With the advent of Windows Vista and Windows 7, we need to consider access rights more than ever. Previously, applications running on windows-based operating systems up to and including XP could just rely on having wide access to perform almost any task. Although many corporate systems are more locked down, the software running on them is generally heavily tailored to do so.

With Windows Vista/7, this locked down approach is brought to the consumer versions of the operating system – by default users do not get administrative privileges – to get these privileges the OS will request confirmation from the user that they are happy for the application to be run in the elevated context. There are 2 main ways of causing the OS to display the prompts:

  1. Creating / updating the application manifest file to include
  2. Launching the application setting the “runas” verb from code

As this blog is centered around c#, lets take a look at the latter.

Once the application is launched, there is no way to elevate the privileges from code. We must therefore look at making sure it is started correctly. Adding the following code to the program start does just this:


            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
            if (!hasAdministrativeRight)
            {
                // relaunch the application with admin rights
                string fileName = Assembly.GetExecutingAssembly().Location;
                ProcessStartInfo processInfo = new ProcessStartInfo();
                processInfo.Verb = "runas";
                processInfo.FileName = fileName;

                try
                {
                    Process.Start(processInfo);
                }
                catch (Win32Exception)
                {
                    // This will be thrown if the user cancels the prompt
                }

                return;
            }

As you can see, what we are actually doing is re-launching the app, setting the ProcessStartInfo.Verb property to “runas”. This automatically causes the OS to prompt the user for admin access.

This can cause a few problems debugging – the easiest way round is to ensure the Visual Studio process is run as an administrator, otherwise we will just launch a new instance of the application whenever we attempt to debug.

, ,

  1. #1 by Erman on July 2, 2018 - 1:59 pm

    Thank you this is great information. !

Leave a comment