programatically run cmd.exe as adminstrator in vis

2019-02-13 21:34发布

问题:

I have a visual studio setup and deployment project. I've added a .cmd script in it. The script would need administrator privilages to run. When user clicks on the setup.exe, UAC prompts the user for Admin permissions. So i assumed that all processes created and called within setup.exe will run in admin capacity. So i made the setup call my console application which contains the following code.

ProcessStartInfo p1 = new ProcessStartInfo();
p1.UseShellExecute = true;
p1.Verb = "runas";
p1.FileName = "cmd.exe";
Process.Start(p1);

So it should've worked as it's run under administrator space.

I want to run cmd.exe through c# process class as an administrator.I'm running windows vista.

I tried didn't work! What can i do!

回答1:

Try executing the runas command:

...

using System.Diagnostics;

...

string UserName = "user name goes here";
ProcessStartInfo p1 = new ProcessStartInfo();
  p1.FileName = "runas";
  p1.Arguments = String.Format("/env /u:{0} cmd", UserName);
Process.Start(p1);

...

(And I don't think you need an explicit UseShellExecute)



回答2:

Just Try this, This worked for Me.

...

using System.Diagnostics;

...

ProcessStartInfo startInfo = new ProcessStartInfo();
  startInfo.UseShellExecute = true;            
  startInfo.Verb = "runas";
  startInfo.Arguments = "/env /user:" + "Administrator" + " cmd";
Process.Start(startInfo);

...

Ashutosh