如何使用c#以管理员身份运行批处理文件来安装windows服务 [英] how to use c# run batch file as Administrator to install windows services

查看:30
本文介绍了如何使用c#以管理员身份运行批处理文件来安装windows服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have create a batch file which use to install my program as windows services. Content of the batch file:

> C:ProjectTestInstallUtil.exe
> "C:ProjectTestROServerServiceServerinDebugmyservices.exe"

目前需要用户右键单击批处理文件并以管理员身份运行"才能成功.我们如何避免以管理员身份运行"?我的意思是我们可以在批处理文件中使用一些命令来告诉 Windows 以管理员身份运行这个批处理文件吗?

Currently it needs the user to right-click the batch file and 'Run as Administrator' in order to success. How do we avoid 'Run as Administrator'? I mean can we use some command in the batch file to tell Windows to run this batch file as administrator?

推荐答案

这种方式过去对我有用:

This way worked for me in the past:

string exe = @"C:ProjectTestInstallUtil.exe";
string args = @"C:ProjectTestROServerServiceServerinDebugmyservices.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)
}

请注意,我在这里直接运行批处理文件中的命令,当然您也可以运行批处理文件本身:

Note that I'm running the commands in your batch file directly here, but of course you can also run the batch file itself:

string bat = @"C:path	oyouratchfile.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;

这篇关于如何使用c#以管理员身份运行批处理文件来安装windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆