Forcing your .NET applcation to run as administrator is actually pretty straightforward. WIth a small web.config update your app will boot as admin by default.
Running .NET as Admin
- First we want to modify the application manifest that is embedded in the program. This will work on Visual Studio 2008 and higher. If your project does not yet have a app manifest file, Go to Project > Add New Item, select "Application Manifest File".
- After creating the file, change the requestedExecutionLevel value as shown below.
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Checking Admin In C#
Below are two methods, the first method AdminRelauncher shows how to re-launch the application with elevated privileges. The second method IsRunAsAdmin is fairly self explanatory.private void AdminRelauncher()
{
if (!IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
proc.Verb = "runas";
try
{
Process.Start(proc);
Application.Current.Shutdown();
}
catch(Exception ex)
{
Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
}
}
}
private bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
Things to Note
- User will always receive a UAC prompt when launching the application
- If you receive the error “ClickOnce does not support the request execution level 'requireAdministrator.'”
- Go to the Security tab, uncheck "Enable ClickOnce security settings"