Start Process with administrator right in C#
I found it, I need to set the Scheduled Task to run the application with highest privileges in General settings.
Run process as administrator from a non-admin application
You must use ShellExecute
. ShellExecute is the only API that knows how to launch Consent.exe
in order to elevate.
Sample (.NET) Source Code
In C#, the way you call ShellExecute
is to use Process.Start
along with UseShellExecute = true
:
private void button1_Click(object sender, EventArgs e)
{
//Public domain; no attribution required.
ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\Notepad.exe");
info.UseShellExecute = true;
info.Verb = "runas";
Process.Start(info);
}
If you want to be a good developer, you can catch when the user clicked No:
private void button1_Click(object sender, EventArgs e)
{
//Public domain; no attribution required.
const int ERROR_CANCELLED = 1223; //The operation was canceled by the user.
ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\Notepad.exe");
info.UseShellExecute = true;
info.Verb = "runas";
try
{
Process.Start(info);
}
catch (Win32Exception ex)
{
if (ex.NativeErrorCode == ERROR_CANCELLED)
MessageBox.Show("Why you no select Yes?");
else
throw;
}
}
Bonus Watching
- UAC - What. How. Why.. The architecture of UAC, explaining that
CreateProcess
cannot do elevation, only create a process.ShellExecute
is the one who knows how to launch Consent.exe, and Consent.exe is the one who checks group policy options.
How to start a process with admin rights
If you have control over the application you're trying to run you should attach a manifest on the executable and require elevated rights.
For this you make a file similar to this and name it the same as your application with .manifest as the extension (e.g. yourApp.exe.manifest):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="appName" type="win32"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"/>
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
</application>
</compatibility>
</assembly>
and then use the mt tool from Visual Studio Command Prompt to attach it
How do I start a process with administrator privileges without my WPF host also runs with admin rights in order to implement file drag & drop?
First, if you need to run just one operation which requires admin rights - that does not mean your whole application should run with admin rights. You need to evelate only for this particular operation. Easiest way to do this is setting UseShellExecute = true when starting your process - then Windows will show usual UAC prompt to user, so that he can confirm evelation. You can describe situation to user before that (in some dialog), or you can put usual UAC icon on button that performs that action (that shield icon).
If that is not an option for you (for example you need redirected output) - you can run another copy of your own application with certain arguments with admin rights (exactly as described above, but not wevtutil, but your own application). This evelated copy will only run wevtutil and exit, doing nothing more.
C# Start Program with ADMIN rights from other program
Try adding this line
process.StartInfo.UseShellExecute = true;
on
using (var process = new Process())
{
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = $".\\ServiceControl.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.Arguments = $"-s {ServiceName} -start";
process.StartInfo.Verb = "runas";
process.Start();
}
Run new process as admin and read standard output
Instead of executing through a new cmd
, try executing the utility directly. And instead of redirecting to a file, redirect the standard output to read it from your program.
In order to run as admin, you'll need to use the admin username and password (taken from here). You'll need to set your method as unsafe
:
unsafe public static void Main(string[] args){
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// set admin user and password
p.StartInfo.UserName = "adminusername";
char[] chArray = "adminpassword".ToCharArray();
System.Security.SecureString str;
fixed (char* chRef = chArray) {
str = new System.Security.SecureString(chRef, chArray.Length);
}
p.StartInfo.Password = str;
// run and redirect as usual
p.StartInfo.FileName = utilityPath;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine(output);
p.WaitForExit();
}
Related Topics
Ado.Net |Datadirectory| Where Is This Documented
Convert Json String to C# Object
Is Floating-Point Math Consistent in C#? Can It Be
Using C#, How Does One Figure Out What Process Locked a File
Await on a Completed Task Same as Task.Result
Json.Net Serialize/Deserialize Derived Types
Finding Holes in 2D Point Sets
Decimal Precision and Scale in Ef Code First
Still Confused About Covariance and Contravariance & In/Out
Why Doesn't C# Allow Static Methods to Implement an Interface
How to Load a .Net Assembly At Runtime and Instantiate a Type Knowing Only the Name
How to Get the Color from a Hexadecimal Color Code Using .Net
How to Convert a C# String Value to an Escaped String Literal