在vista,C#中以管理员身份以编程方式运行cmd.exe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/667381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:32:19  来源:igfitidea点击:

programmatically run cmd.exe as administrator in vista, C#

c#windows-vistaprocesscmdadministrator

提问by Anirudh Goel

I have a visual studio setup and deployment project. I've added a .cmd script in it. The script would need administrator privileges 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.

我有一个 Visual Studio 设置和部署项目。我在其中添加了一个 .cmd 脚本。该脚本需要管理员权限才能运行。当用户单击 setup.exe 时,UAC 会提示用户输入管理员权限。所以我假设在 setup.exe 中创建和调用的所有进程都将以管理员身份运行。所以我进行了设置调用我的控制台应用程序,其中包含以下代码。

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.

我想以管理员身份通过 c# 进程类运行 cmd.exe。我正在运行 windows vista。

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

我试了没用!我能做什么?

采纳答案by Lucas Jones

Try executing the runascommand:

尝试执行runas命令

...

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)

(而且我认为您不需要明确的 UseShellExecute)

回答by Lucas Jones

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

阿舒托什