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

Wil*_*son 4 c# windows service batch-file

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

> C:\Project\Test\InstallUtil.exe
> "C:\Project\Test\ROServerService\Server\bin\Debug\myservices.exe"
Run Code Online (Sandbox Code Playgroud)

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

Mas*_*r_T 6

这种方式过去对我有用:

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)
}
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)