how to use c# run batch file as Administrator to install windows services

前端 未结 1 566
名媛妹妹
名媛妹妹 2021-01-06 12:27

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

> C:\\Project\\Test\\InstallUtil.exe
> \"C:\         


        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-06 13:08

    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;
    

    0 讨论(0)
提交回复
热议问题