"ClickOnce does not support the request execution level 'requireAdministrator.'" - c#

So I was writing an application that requires access to the registry.
I had not touched any build settings, wanting to get the thing working before I added the other touches, such as a description or name.
Out of the blue, I get an error that will not go away. ClickOnce does not support the request execution level 'requireAdministrator'. Now, I hadn't touched ClickOnce in this application. All I had done was include a manifest file requesting these permissions.
My problem now is that this error will not go away, and I cannot compile my program. Any advice on what to do? (Side note: I am about to go to bed, so I will check this tomorrow afternoon).

Edit: This comment gives a good answer, too.
Click once appears to get enabled whenever you click "Publish", whether you want it to or not! If you are using "requireAdministrator" then it appears that you cannot use ClickOnce, and therefore cannot "Publish" your project.
Original:
Turns out that under the Security tab, "Enable ClickOnce security settings" was checked. Even though I didn't check it.
Anyway, unchecking that stopped ClickOnce giving me errors. That took a while to find...

I know this an old question but I came here two years later so:
You can disable the ClicKOnce from the Security tab on project properites to help the issue; see below:

If you ever use the publishing wizard, or 'Publish Now', the click-once checkbox gets automatically selected...

I know this is old but I stumbled across it looking for answers. In my case, I AM using the publish function and I need to keep using it. I also need access to admin capabilities. So for that reason, none of the above answers worked for me.
I ended up adding a method to the very start of my application that checks if it's being run as an administrator and if it isn't, relaunch itself as an admin. To do this, you need the following references added.
using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
Then you will need to put this somewhere that your main method has handy access to. I'm using WPF so I added it to MainWindow.xaml.cs but you can add it anywhere early on in your code. Just remember to add "static" to these methods should you need it.
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()
{
try
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (Exception)
{
return false;
}
}
Lastly, at the start of your program, add a reference to the method. In my case, I added it to MainWindow but adding it to Main works too.
public MainWindow()
{
InitializeComponent();
AdminRelauncher(); //This is the only important line here, add it to a place it gets run early on.
}
Hope this helps!
For .NET Core and .NET 5+
If you're stumbling upon this in the 20s, this is how you would change the above to work with .NET Core and .NET 5+
The only function that needs changing is the AdminRelauncher and it should look like this instead.
private static void AdminRelauncher()
{
if (!IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().Location.Replace(".dll", ".exe");
proc.Verb = "runas";
try
{
Process.Start(proc);
Environment.Exit(0);
}
catch (Exception ex)
{
Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
}
}
}
The only big changes is as someone pointed out Application isn't always available. So Environment.Exit(0) can replace it and the filename needs to replace .exe with .dll. This has been tested as of .NET 6

For those who use uncheck "Enable ClickOnce security settings" can't work, to try the method I find.
First, leave your app.manifest requestedExecutionLevel item as is:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
And then you edit your Program.cs file like this:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
using System.Windows.Forms;
restruct main method like:
static void Main()
{
var wi = WindowsIdentity.GetCurrent();
var wp = new WindowsPrincipal(wi);
bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);
if (!runAsAdmin)
{
// It is not possible to launch a ClickOnce app as administrator directly,
// so instead we launch the app as administrator in a new process.
var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase);
// The following properties run the new process as administrator
processInfo.UseShellExecute = true;
processInfo.Verb = "runas";
// Start the new process
try
{
Process.Start(processInfo);
}
catch (Exception)
{
// The user did not allow the application to run as administrator
MessageBox.Show("Sorry, but I don't seem to be able to start " +
"this program with administrator rights!");
}
// Shut down the current process
Application.Exit();
}
else
{
// We are running as administrator
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
It works on Windows 10 and Visual Studio 2019!

This action can be achieved by selecting "Enable ClickOnce security settings" (since it cannot be "unchecked" during a Publish, as stated) and then by selecting "This is a partial trust application". "Local Intranet" will be automatically selected in the drop-down menu which is perfectly fine.
Save your changes, Publish the application, done-skis. :-)

I have the same problem s I resolve it by unchecking the "Enable ClickOnce security settings"
To Find this option in Visual Studio Right Click on your Project ==>properties==>Select Security==> Enable ClickOnce security settings (This option was already checked so I unchecked it and my problem get resolved).

Here is the code snippet for VB.NET
If Not New WindowsPrincipal(WindowsIdentity.GetCurrent).IsInRole(WindowsBuiltInRole.Administrator) Then
Process.Start(New ProcessStartInfo With { _
.UseShellExecute = True, _
.WorkingDirectory = Environment.CurrentDirectory, _
.FileName = Assembly.GetEntryAssembly.CodeBase, _
.Verb = "runas"})
EDIT: But if you deploy in this way, some AV-Software blocks your code.

For anyone who's run into this, I thought I'd contribute what ended up working for me.
Yep, the 'Enable ClickOnce security settings' option automatically gets re-checked, if you un-check it, when you do Build > Publish .
For me, I don't need to 'Publish' -- it's a simple, portable .exe that creates Scheduled Tasks for my users and I needed to make sure it elevated, even when logged-in as an Administrator.
So I just grabbed my latest .exe from \bin\Release and that's what gets deployed on my clients' systems.
Worked just as expected -- i.e. when I put it on a system w/ UAC enabled/at its highest setting, the .exe has the 'shield' on it, and when I run it, even when logged-in as an Administrator, it elevates and I get the UAC prompt.
My little task scheduler app is now able to create the task without getting an 'Access Denied' error (which previously, could only be worked-around by right-clicking the .exe and clicking Run as Administrator).

Take a look in your app.Manifest file and you'll see this:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
There's instructions there in the comments, but just deleting the "requireAdministrator" and insert this in is place solved the problem for me:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />

just
Imports System.security
and
U will get no error and your application will be run as admin

Related

C# Winform Registry set and get functions appear to work, but don't actually change the registry

I'm trying to use this registry hack I found online:
;Disables F1 key - Help and Support - in Windows 10
;Ramesh Srinivasan, Winhelponline.com
[HKEY_CURRENT_USER\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win32]
#=""
[HKEY_CURRENT_USER\SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64]
#=""
When I run it as a .reg command via Windows Explorer and watch the registry with regedit, it works as intended. Removing it is another registry file that simply removes the \0 subkey (and win32 and 64 with it). I'm trying to emulate this function with C# in a Winform using .net CORE:
private void CheckF1()
{
// Registry data from ;Ramesh Srinivasan, Winhelponline.com
RegistryKey F1key = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Classes\TypeLib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0");
// EGADS! It's active!
if (F1key == null)
{
fckF1RestoreBtn.Enabled = false;
fckF1KillBtn.Enabled = true;
fckF1Status.Text = "That creepy bugger is waiting and watching.";
}
else
{
fckF1RestoreBtn.Enabled = true;
fckF1KillBtn.Enabled = false;
fckF1Status.Text = "The F1-Help function had been put in it's place.";
}
}
private void fckF1KillBtn_Click(object sender, EventArgs e)
{
Registry.CurrentUser.CreateSubKey(#"SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win32");
Registry.CurrentUser.CreateSubKey(#"SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0\win64");
CheckF1();
}
private void fckF1RestoreBtn_Click(object sender, EventArgs e)
{
Registry.CurrentUser.DeleteSubKeyTree(#"SOFTWARE\Classes\Typelib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0");
CheckF1();
}
Weirdly the code "sees" a setting and responds like it should. Even to the point that whichever toggle position it was in on close it remembers when I load the file again. It's almost like it's playing along to screw with me. Regardless, when I watch the registry, none of my code has any actual effect though by all appearances it seems to work otherwise (it doesn't actually of course because the registry change isn't happening).
NOTE: I have already updated my manifest file for the project to include elevated permissions:
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
Here's the breakpoint on the test statement to see if the subkeys are there that shows they are:
Meanwhile the registry location for the exact path shown in the debug doesn't have the 1.0\0 path at all:
I don't know how the code is reading phantom values. Someone closed my previous question pointing to another answer that didn't have any effect (Registry key deleted but still getting value from registry c#):
"Prefer 32 bit" was never checked for my project in the first place
Modifying my code as recommended had no effect
var key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)
.OpenSubKey(#"SOFTWARE\WOW6432Node\Classes\TypeLib\{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0");
Adding "Wow64Node" to the path makes no difference in execution.
EXPECTED BEHAVIOR
Checking to see if the HKEY_CURRENT_USER\SOFTWARE\Classes\Typelib{8cec5860-07a1-11d9-b15e-000d56bfe6ee}\1.0\0 path is present should return null if the \0 path is not present
Adding and removing the subkeys should show in the registry
So apparently HKEY_CURRENT_USERS is an alias. When the above code runs, it updates in HKEY_USERS under the specific logged in user. There's a question that talks about this behavior here: write registry to hkey_current_user instead of hkey_users
That said, the code appears to work, it's just that the registry doesn't update HKCU like when you run .reg commands. To verify it was working, I'd run the toggle that kills the keys then click them in Regedit and it would say they didn't exist. When I toggled back, I could click on them. So basically, it works (not sure if it required the "using" blocks as others suggested, but I see no reason to take them out).
Now my problem is that it points to the admin user and NOT the regular user because I'm running it and regedit as admin. It took forever to determine this based on running regedit as user in one case and admin in another. Bottom line, this won't work and I'll probably end up running .reg files in the command line instead.

Elevated executable can't find OS Tool

I'm trying to create a shortcut in my C# WinForm application for users to launch Microsoft's "Digitizer to Monitor Mapping Tool" (MultiDigiMon.exe). However it seems that even if ran as an administrator my applications or cmd processes launched from it can not find the executable in question and I have no idea why.
My Short cut consists of a simple button with the click event hooked to the fallowing function.
private void TouchButton_Click(object sender, EventArgs e)
{
ProcessStartInfo start = new ProcessStartInfo("C:\\Windows\\System32\\cmd.exe");
start.WorkingDirectory = "C:\\Windows\\System32";
start.CreateNoWindow = false;
start.UseShellExecute = false;
//start.Arguments = "/K \"cd C:\\Windows\\System32 && MultiDigiMon.exe -touch\"";
Process.Start(start);
}
In my experience on Win10 systems, MultiDigiMon.exe can be always be found in C:\Windows\System32 (assuming the C drive is your root). Additionally the arguments line above was commented out to make the following screen shots as identical as possible.
On the left is the command prompt launched using the above code and on the right is a command prompt launched by typing cmd in to the OS's taskbar and and running the first result as administrator. As you can see both promps are marked as administrator but the left fails to launch MultiDigiMon.exe and won't even list the file exist using the dir command. the right seems to have no issue with either command. (MultiDigiMon.exe dose not seem to do anything at all if multiple touch screen devices are not connected and I do not believe that it give any text output especially if successful).
Finally I have also checked the permission on MultiDigiMon.exe and (with the exception of TrustedInstaller who has full control) everybody has read and execute right. Could someone explain why I can't launch MultiDigimon.exe form the left prompt or directly from my application?
As commented on by RbMm the issue was that since my application was being compiled to run on any cpu it was treated as a 32 bit application by the file system and redirected all access to the System32 directory to SysWOW64.
To get around this you can substitute "System32" width "Sysnative" as discussed here. In my case my final code ended up looking like the fallowing.
private void TouchButton_Click(object sender, EventArgs e)
{
ProcessStartInfo start = new ProcessStartInfo("C:\\Windows\\Sysnative\\MultiDigiMon.exe");
start.WorkingDirectory = "C:\\Windows\\System32";
start.CreateNoWindow = false;
start.UseShellExecute = false;
start.Arguments = "-touch";
Process.Start(start);
}

fileStream.WriteByte c# can't write in directory. It's need admin permission [duplicate]

Once my program is installed on a client machine, how do I force my program to run as an administrator on Windows 7?
You'll want to modify the manifest that gets embedded in the program. This works on Visual Studio 2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <requestedExecutionLevel> element to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
The user gets the UAC prompt when they start the program. Use wisely; their patience can wear out quickly.
Adding a requestedExecutionLevel element to your manifest is only half the battle; you have to remember that UAC can be turned off. If it is, you have to perform the check the old school way and put up an error dialog if the user is not administrator (call IsInRole(WindowsBuiltInRole.Administrator) on your thread's CurrentPrincipal).
The detailed steps are as follow.
Add application manifest file to project
Change application setting to "app.manifest"
Update tag of "requestedExecutionLevel" to requireAdministrator.
Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security
I implemented some code to do it manually:
using System.Security.Principal;
public bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}
You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.
You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).
While working on Visual Studio 2008, right click on Project -> Add New Item and then chose Application Manifest File.
In the manifest file, you will find the tag requestedExecutionLevel, and you may set the level to three values:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
OR
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
OR
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
To set your application to run as administrator, you have to chose the middle one.
Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by #NG.. And then open the application again and close the current one.
I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.
Note in the below code NeedsToRunAsAdmin is a method that detects if under current conditions admin privileges are required. If this returns false the code will not elevate itself. This is a major advantage of this approach over the others.
Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.
private static void Main(string[] args)
{
if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
foreach (string arg in args)
{
proc.Arguments += String.Format("\"{0}\" ", arg);
}
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
}
}
else
{
//Normal program logic...
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
As per
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.
Next, right click project
Add new Item
Last, find and click Application Manifest File
In Visual Studio 2010 right click your project name.
Hit "View Windows Settings", this generates and opens a file called "app.manifest".
Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.
You can create the manifest using ClickOnce Security Settings, and then disable it:
Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings
After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings option
Open that file and change this line :
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will make the program require administrator privileges.
In case you want a code-only solution for some reason, here's a standalone class file. Just call "AdminRelauncher.RelaunchIfNotAdmin()" at application start:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
public static class AdminRelauncher
{
public static void RelaunchIfNotAdmin()
{
if (!RunningAsAdmin())
{
Console.WriteLine("Running as admin required!");
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
proc.Verb = "runas";
try
{
Process.Start(proc);
Environment.Exit(0);
}
catch (Exception ex)
{
Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
Environment.Exit(0);
}
}
}
private static bool RunningAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
THIS DOES NOT FORCE APPLICATION TO WORK AS ADMINISTRATOR.
This is a simplified version of the this answer, above by #NG
public bool IsUserAdministrator()
{
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}

C# console program has to run in Administrator mode always [duplicate]

Once my program is installed on a client machine, how do I force my program to run as an administrator on Windows 7?
You'll want to modify the manifest that gets embedded in the program. This works on Visual Studio 2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <requestedExecutionLevel> element to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
The user gets the UAC prompt when they start the program. Use wisely; their patience can wear out quickly.
Adding a requestedExecutionLevel element to your manifest is only half the battle; you have to remember that UAC can be turned off. If it is, you have to perform the check the old school way and put up an error dialog if the user is not administrator (call IsInRole(WindowsBuiltInRole.Administrator) on your thread's CurrentPrincipal).
The detailed steps are as follow.
Add application manifest file to project
Change application setting to "app.manifest"
Update tag of "requestedExecutionLevel" to requireAdministrator.
Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security
I implemented some code to do it manually:
using System.Security.Principal;
public bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}
You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.
You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).
While working on Visual Studio 2008, right click on Project -> Add New Item and then chose Application Manifest File.
In the manifest file, you will find the tag requestedExecutionLevel, and you may set the level to three values:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
OR
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
OR
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
To set your application to run as administrator, you have to chose the middle one.
Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by #NG.. And then open the application again and close the current one.
I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.
Note in the below code NeedsToRunAsAdmin is a method that detects if under current conditions admin privileges are required. If this returns false the code will not elevate itself. This is a major advantage of this approach over the others.
Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.
private static void Main(string[] args)
{
if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
foreach (string arg in args)
{
proc.Arguments += String.Format("\"{0}\" ", arg);
}
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
}
}
else
{
//Normal program logic...
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
As per
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.
Next, right click project
Add new Item
Last, find and click Application Manifest File
In Visual Studio 2010 right click your project name.
Hit "View Windows Settings", this generates and opens a file called "app.manifest".
Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.
You can create the manifest using ClickOnce Security Settings, and then disable it:
Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings
After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings option
Open that file and change this line :
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will make the program require administrator privileges.
In case you want a code-only solution for some reason, here's a standalone class file. Just call "AdminRelauncher.RelaunchIfNotAdmin()" at application start:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
public static class AdminRelauncher
{
public static void RelaunchIfNotAdmin()
{
if (!RunningAsAdmin())
{
Console.WriteLine("Running as admin required!");
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
proc.Verb = "runas";
try
{
Process.Start(proc);
Environment.Exit(0);
}
catch (Exception ex)
{
Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
Environment.Exit(0);
}
}
}
private static bool RunningAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
THIS DOES NOT FORCE APPLICATION TO WORK AS ADMINISTRATOR.
This is a simplified version of the this answer, above by #NG
public bool IsUserAdministrator()
{
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}

How to force the system to run as Administrator with C# [duplicate]

Once my program is installed on a client machine, how do I force my program to run as an administrator on Windows 7?
You'll want to modify the manifest that gets embedded in the program. This works on Visual Studio 2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <requestedExecutionLevel> element to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
The user gets the UAC prompt when they start the program. Use wisely; their patience can wear out quickly.
Adding a requestedExecutionLevel element to your manifest is only half the battle; you have to remember that UAC can be turned off. If it is, you have to perform the check the old school way and put up an error dialog if the user is not administrator (call IsInRole(WindowsBuiltInRole.Administrator) on your thread's CurrentPrincipal).
The detailed steps are as follow.
Add application manifest file to project
Change application setting to "app.manifest"
Update tag of "requestedExecutionLevel" to requireAdministrator.
Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security
I implemented some code to do it manually:
using System.Security.Principal;
public bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}
You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.
You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).
While working on Visual Studio 2008, right click on Project -> Add New Item and then chose Application Manifest File.
In the manifest file, you will find the tag requestedExecutionLevel, and you may set the level to three values:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
OR
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
OR
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
To set your application to run as administrator, you have to chose the middle one.
Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by #NG.. And then open the application again and close the current one.
I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.
Note in the below code NeedsToRunAsAdmin is a method that detects if under current conditions admin privileges are required. If this returns false the code will not elevate itself. This is a major advantage of this approach over the others.
Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.
private static void Main(string[] args)
{
if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
foreach (string arg in args)
{
proc.Arguments += String.Format("\"{0}\" ", arg);
}
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
}
}
else
{
//Normal program logic...
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
As per
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.
Next, right click project
Add new Item
Last, find and click Application Manifest File
In Visual Studio 2010 right click your project name.
Hit "View Windows Settings", this generates and opens a file called "app.manifest".
Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.
You can create the manifest using ClickOnce Security Settings, and then disable it:
Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings
After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings option
Open that file and change this line :
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will make the program require administrator privileges.
In case you want a code-only solution for some reason, here's a standalone class file. Just call "AdminRelauncher.RelaunchIfNotAdmin()" at application start:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
public static class AdminRelauncher
{
public static void RelaunchIfNotAdmin()
{
if (!RunningAsAdmin())
{
Console.WriteLine("Running as admin required!");
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
proc.Verb = "runas";
try
{
Process.Start(proc);
Environment.Exit(0);
}
catch (Exception ex)
{
Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
Environment.Exit(0);
}
}
}
private static bool RunningAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
THIS DOES NOT FORCE APPLICATION TO WORK AS ADMINISTRATOR.
This is a simplified version of the this answer, above by #NG
public bool IsUserAdministrator()
{
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}

Categories

Resources