I’m building a small tool (more about it in a later post). What's important to successfully run this tool is that it should be executed with administrative privileges. In this post I share 2 ways how you can make this happen.
Remark: Be aware that both methods I show only work on Windows.
Check if the app is running using administrative privileges
My original solution was to check if the application was running with administrative privileges and exit if this was not the case.
Here is the code I used to check this:
using System; | |
using System.DirectoryServices.AccountManagement; | |
using System.Linq; | |
using System.Security.Principal; | |
using Microsoft.Web.Administration; | |
using System.Security.Principal; | |
class Program | |
{ | |
static void Main() | |
{ | |
Console.WriteLine("Adding IIS AppPool users to Performance Log Users and Performance Monitor Users groups."); | |
if (!IsAdministrator()) | |
{ | |
Console.WriteLine("Run this tool as an administrator on the IIS instance directly."); | |
return; | |
} | |
Console.WriteLine("Running as administrator."); | |
Console.WriteLine("Press any key to continue..."); | |
Console.ReadLine(); | |
} | |
static bool IsAdministrator() | |
{ | |
using WindowsIdentity identity = WindowsIdentity.GetCurrent(); | |
WindowsPrincipal principal = new WindowsPrincipal(identity); | |
return principal.IsInRole(WindowsBuiltInRole.Administrator); | |
} | |
} |
This only checks if the current process is running as Administrator.
Request to run the app as administrator through UAC
The solution above works but wouldn’t it be more user friendly if we use UAC (User Account Control) and ask the user permission to elevate the permissions at startup?
This can be done by adding an App.Manifest file:
Inside this file add the following XML:
<?xml version="1.0" encoding="utf-8"?> | |
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> | |
<assemblyIdentity version="1.0.0.0" name="AppPoolTool"/> | |
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> | |
<security> | |
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> | |
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> | |
</requestedPrivileges> | |
</security> | |
</trustInfo> | |
</assembly> |
If we now run our program, we get a prompt to elevate the permissions:
Nice!