且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-02-12 09:53:49

这种方式过去对我有用:

This way worked for me in the past:

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)
}

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

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\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;