如何使用C#以管理员身份运行批处理文件来安装Windows服务

5

我创建了一个批处理文件,用于将我的程序安装为Windows服务。

批处理文件的内容如下:

> C:\Project\Test\InstallUtil.exe
> "C:\Project\Test\ROServerService\Server\bin\Debug\myservices.exe"

目前需要用户右键单击批处理文件并选择“以管理员身份运行”才能成功。我们如何避免“以管理员身份运行”?我的意思是,我们是否可以在批处理文件中使用一些命令告诉Windows以管理员身份运行此批处理文件?

1个回答

9
这是我过去使用的方法:
string exe = @"C:\Project\Test\InstallUtil.exe";
string args = @"C:\Project\Test\ROServerService\Server\bin\Debug\myservices.exe";
var psi = new ProcessStartInfo();
psi.CreateNoWindow = true; //This hides the dos-style black window that the command prompt usually shows
psi.FileName = @"cmd.exe";
psi.Verb = "runas"; //This is what actually runs the command as administrator
psi.Arguments = "/C " + exe + " " + args;
try {
    var process = new Process();
    process.StartInfo = psi;
    process.Start();
    process.WaitForExit();
}
catch (Exception){
    //If you are here the user clicked decline to grant admin privileges (or he's not administrator)
}

请注意,我在此直接运行您批处理文件中的命令,但是您当然也可以运行批处理文件本身:
string bat = @"C:\path\to\your\batch\file.bat";
var psi = new ProcessStartInfo();
psi.CreateNoWindow = true; //This hides the dos-style black window that the command prompt usually shows
psi.FileName = @"cmd.exe";
psi.Verb = "runas"; //This is what actually runs the command as administrator
psi.Arguments = "/C " + bat;

我们如何在客户端的管理员模式下运行这个程序? - Amit Sinha
@EnigmaticMind:我不明白你的问题...代码已经在管理员模式下运行命令了。你到底有什么问题? - Master_T
我将上述代码放在了Web应用程序中,并在批处理文件的路径中提供了服务器IP(客户端IP)+路径。但是它没有起作用。所以问题是,这段代码是否适用于Web应用程序。 - Amit Sinha
你不能使用这段代码在不同的机器上运行进程/批处理,这段代码只能在本地机器上运行。 - Master_T
为了我的使用,我还需要设置 "psi.UseShellExecute = true;"。我还创建了一个新进程,并将 psi 设置为 process.startInfo。之后执行 process.Start()。 - Kai W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接