Recently I was writing some code to allow a program to register
itself to start with Windows for all users. On Windows 7 with
User Account Control (UAC) enabled, trying to write to the
relevant registry key without having elevated permissions throws
UnauthorizedAccessException exception. If you want to make
these sorts of modifications to a system, the application needs
to be running as an administrator.
Checking if your application is running with elevated permissions
To check if your application is currently running with elevated
permissions, you simply need to see if the current user belongs
Administrator user group.
Running an application as an administrator
While it might be possible to elevate your applications process
LogonUser API, this requires user names and passwords,
and isn't a trivial task. So we'll ignore this approach in
favour of something much more simplistic and less likely to go
wrong, not to mention not requiring admin passwords.
You're probably already aware that there are various "verbs"
predefined for dealing with specific actions relating to
interaction with a file, such as
open. While these
verbs are normally configured on file associations in the
Windows Registry, you can also force a process to be run under
the administration account by specifying the
Note: Specifying this verb in Windows XP displays a dialog allowing a user to be selected. Unfortunately this means that it's possible for the spawned application to not have the required permissions either - remember to check that you have permission to do an action before actually attempting it!
For my scenario, the core application shouldn't need to run in elevated mode, so I decided to create a generic stub program which would accept a number of arguments for if the startup program should be registered or unregistered, and the title and location used to perform the action. Then the main application simply spawned this process in administration mode to apply the users choice.
Note: Although I haven't included it in the example above, you may wish to handle the
Win32Exceptionthat can be thrown by the
Process.Startmethod. If the user cancels the UAC prompt, this exception will be automatically thrown with the
ERROR_CANCELLED(1223) error code.
runas verb specified, the application is now run in
elevated mode, and the operating system asks the user for
permission to continue. Unfortunately, if your application isn't
signed, then you get a scarier version of the prompt, as
displayed above. If your application is signed, then you'll get
something similar to the screenshot below.
- 2011-11-27 - First published
- 2020-11-21 - Updated formatting
Like what you're reading? Perhaps you like to buy us a coffee?